Sending/receiving weird data
Im sending data on network via sockets like this: (broadcast)
void sendBroad(char *dstIP, char *localIP, char *localMAC)
{
int sock; /* Socket */
struct sockaddr_in broadcastAddr; /* Broadcast address */
int broadcastPermission; /* Socket opt to set permission to broadcast */
unsigned int dataLen;
char data[100]={0};
strcat(data, localIP);
strcat(dat开发者_StackOverflow社区a, " ");
strcat(data, localMAC);
strcat(data, " ");
/* Create socket for sending/receiving datagrams */
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
perror("socket() failed");
/* Set socket to allow broadcast */
broadcastPermission = 1;
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission,
sizeof(broadcastPermission)) < 0)
perror("setsockopt() failed");
/* Construct local address structure */
memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */
broadcastAddr.sin_family = AF_INET; /* Internet address family */
broadcastAddr.sin_addr.s_addr = inet_addr(dstIP); /* Broadcast IP address */
broadcastAddr.sin_port = htons(BroadcastPort); /* Broadcast port */
dataLen = strlen(data);
int j;
for (j=0; j<1; j++) /* 3krat a dost */
{
/* Broadcast localIP in datagram to clients */
if (sendto(sock, data, dataLen, 0, (struct sockaddr *)
&broadcastAddr, sizeof(broadcastAddr)) != dataLen)
perror("sendto() sent a different number of bytes than expected");
}
/* NOT REACHED */
}
but I always get some weird chars in the begining when receiving, like:
X.?192.168.....
When I try to send this data 6 times, just once I get data starting with 192..., other 5 strings starts with those weird chars. Any idea what is happening here?
Thanks
char data[100];
is not initialized. Accordingly, you are concatenating to the end of some undefined garbage, not to the end of an empty string. This is obviously undefined behaviour as it is not guaranteed that a '\0' appears anywhere within the reserved space (to say nothing of the fact that it's just plain undefined behaviour and the compiler may actually do what it wishes if/when it detects this).
char data[100] = {0};
should do the trick.
精彩评论