i'm writing program interface machine running java, , need send character arrays on network. on receiving end, java program uses datainputstream's readchar() function , expects characters. however, since characters stored 1 byte in c, i'm having trouble writing network.
how go converting this?
the actual protocol specification so:
short: contains length of char array char 1, 2, 3...: characters in array
for background information, short conversion so:
char *getbytesshort(short data) { short net_data = net_htons(data); char *ptr = (char *) malloc(sizeof(short)); memcpy(ptr, &net_data, sizeof(short)); return ptr; }
i've tested on receiving end in java, , short sent on correctly correct length, character array not.
thanks in advance!
there many ways it. want construct buffer containing of data , pass onto send(2)
system call send along socket.
the wire format data big-endian (aka network byte order), should make sure store values most-significant byte first. recommend manually constructing byte buffer avoid endianness issues local system (see the byte order fallacy), e.g.:
uint16_t datalen = ...; // length of data, in characters uint16_t *chardata = ...; // character array // constructor packet data buffer send. error checking omitted // expository purposes. size_t packetsize = 2 + datalen * 2; uint8_t *packet = malloc(packetsize); // copy length buffer, big-endian packet[0] = (uint8_t)(datalen >> 8); packet[1] = (uint8_t)(datalen & 0xff); // copy each character buffer, big-endian (uint16_t = 0; < datalen; i++) { packet[2 + 2*i] = (uint8_t)(chardata[i] >> 8); packet[2 + 2*i + 1] = (uint8_t)(chardata[i] & 0xff); } // we're done -- send packet send(sockfd, packet, packetsize, 0);