recv与原始套接字

时间:2013-02-26 15:04:09

标签: c sockets recv

我正在尝试从socket中恢复原始数据包并失败。邮件仅在服务器站点上发送数据包时打印。没有数据包传输时 - 程序挂起在recv(套接字处于同步模式)。

问题是打印消息是“缓冲区”但没有接收到数据。

#include <sys/socket.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>

#define ETH_FRAME_LEN 1400

int main(){

    int s; /*socketdescriptor*/

    s = socket(PF_PACKET, SOCK_RAW, htons(0x88b5));
    if (s == -1) { perror("socket"); }

        struct sockaddr_ll socket_address;
    int r;
    char ifName[IFNAMSIZ] = "eth0";

    struct ifreq ifr;  
        strncpy((char *)ifr.ifr_name ,device , IFNAMSIZ); 

    /* Get the index of the interface to send on */
    memset(&if_idx, 0, sizeof(struct ifreq));
    strncpy(if_idx.ifr_name, ifName, IFNAMSIZ-1);
    if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0)
        perror("SIOCGIFINDEX");

    /* Get the MAC address of the interface to send on */   
    memset(&if_mac, 0, sizeof(struct ifreq));
    strncpy(if_mac.ifr_name, ifName, IFNAMSIZ-1);
    if (ioctl(sockfd, SIOCGIFHWADDR, &if_mac) < 0)
        perror("SIOCGIFHWADDR");

        memset(&socket_address, 0, sizeof(socket_address));
        socket_address.sll_ifindex = ifr.if_idx;
        socket_address.sll_protocol = htons(0x88b5);
        socket_address.sll_family = PF_PACKET;
        socket_address.sll_pkttype = PACKET_OUTGOING;

        r = bind(s, (struct sockaddr*)&socket_address,
                    sizeof(socket_address));
    if ( r < 0) { perror("bind")};

    void* buffer = (void*)malloc(ETH_FRAME_LEN); /*Buffer for ethernet frame*/
    int length = 0; /*length of the received frame*/ 

    length = recv(s, buffer, ETH_FRAME_LEN, 0,);
    if (length == -1) { perror("recvfrom"); }
    printf ("buffer %s\n", buffer);

}

1 个答案:

答案 0 :(得分:2)

您只能将%s格式说明符用于C样式字符串。您不能将它用于任意二进制数据。怎么知道要打印多少个字符?您在名为length的变量中有长度。你需要打印那么多角色。例如:

for (int i = 0; i < length; ++i)
     putchar(((char *)buffer)[i]);

这可能看起来像垃圾,因为你输出了一堆不可打印的字符。也许你想要这样的东西:

void print(void *buf, int length)
{
      char *bp = (char *) buf;
      for (int i = 0; i < length; ++i)
          putchar( isprintf(bp[i]) ? bp[i] : '.' );
      putchar('\n');
}

这将用点替换不可打印的字符。