问题:

     Centos7多网卡,抓包时发现某网卡上有UDP包,但是用程序recvfrom无法接收到消息。

解决步骤:

1.确认防火墙是否关闭;

已关闭

2.确认网卡是否开启过滤:cat /proc/sys/net/ipv4/conf/ethxxx/rp_filter    (ethxxx是网卡名称)

结果:已关闭(当然此配置项只影响组播,这是病急乱投医)

3.随便找一个服务端和客户端的代码,测试是否能正常进行udp通信;  

结果发现完全正常。

server.cpp

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        printf("Usage: %s port\n", argv[0]);
        exit(1);
    }
    printf("Welcome! This is a UDP server, I can only received message from client and reply with same message\n");
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    int sock;
    if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket");
        exit(1);
    }
    if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("bind");
        exit(1);
    }
    char buff[409600];
    struct sockaddr_in clientAddr;
    int n;
    unsigned int len = sizeof(clientAddr);
    while (1)
    {
        n = recvfrom(sock, buff, 409600, 0, (struct sockaddr*)&clientAddr, &len);
        if (n>0)
        {
            buff[n] = 0;
            printf("%s %u says: %s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buff);
            n = sendto(sock, buff, n, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr));
            if (n < 0)
            {
                perror("sendto");
                break;
            }
        }
        else
        {
            perror("recv");
            break;
        }
    }
    return 0;
}
View Code

相关文章:

  • 2021-05-18
  • 2021-05-31
  • 2021-11-05
  • 2021-08-03
  • 2021-04-07
  • 2022-12-23
  • 2021-04-03
  • 2022-12-23
猜你喜欢
  • 2021-05-20
  • 2022-12-23
  • 2021-04-01
  • 2021-12-04
  • 2022-12-23
  • 2021-12-09
相关资源
相似解决方案