发送/接收奇怪的数据

时间:2011-07-22 19:05:08

标签: c linux sockets

我通过这样的套接字在网络上发送数据:(广播)

    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(data, " ");
    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 */
}

但是在接收时我总是会得到一些奇怪的字符,例如:

X.?192.168.....

当我尝试发送这些数据6次时,只有一次我从192开始获取数据...,其他5个字符串从那些奇怪的字符开始。知道这里发生了什么吗?

由于

1 个答案:

答案 0 :(得分:7)

char data[100];未初始化。因此,您将连接到某些未定义的垃圾的末尾,而不是连接到空字符串的末尾。这显然是未定义的行为,因为不能保证'\ 0'出现在保留空间内的任何地方(更不用说它只是普通的未定义行为,并且如果/当它检测到这个时编译器可能实际上做它想要的事情) )。

char data[100] = {0};应该可以解决问题。