【问题标题】:different ports in netstat and programnetstat 和 program 中的不同端口
【发布时间】:2021-09-29 22:07:24
【问题描述】:

我有这个简单的 TCP 回显服务器,每当客户端连接到它时,它都会显示客户端的 IP 和端口。但是当我运行netstat -a 时,会显示客户端的不同端口。我在同一台计算机上运行服务器和客户端。

在我的程序中,它显示client connected: 127.0.0.1:34997,但netstat -a|grep 6969的结果是:

tcp        0      0 0.0.0.0:6969            0.0.0.0:*               LISTEN     
tcp        0      0 localhost:46472         localhost:6969          ESTABLISHED
tcp        0      0 localhost:6969          localhost:46472         ESTABLISHED 

回显服务器的代码是:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>

int main(int argc,char **argv){
    int listenfd,confd,n;
    struct sockaddr_in server,client;
    pid_t pid;
    char buffer[100];

    memset(&server,0,sizeof server);
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=htonl(INADDR_ANY);
    server.sin_port=htons(6969);

    listenfd=socket(AF_INET,SOCK_STREAM,0);
    
    if(bind(listenfd,(struct sockaddr *)&server,sizeof server)==-1){
        perror("bind error");return-1;
    }

    if(listen(listenfd,20)==-1){
        perror("listen error");return -1;
    }
    printf("listening for connection..\n");

    for(;;){
        socklen_t cllen = sizeof(client);
        confd=accept(listenfd,(struct sockaddr *)&client,&cllen);
        
        
        if((pid=fork())==0){    
            printf("client connected: %s:%d\n",inet_ntoa(client.sin_addr),client.sin_port);
            close(listenfd);
            for(;;){
                n=read(confd,&buffer,sizeof buffer);
                if(n==0) break;
                write(confd,&buffer,n);
            }
            printf("client disconnected: %s:%d",inet_ntoa(client.sin_addr),client.sin_port);
            exit(0);
        }
        close(confd);

    }
}

【问题讨论】:

  • 您能否向我们展示您的代码,以便我们可以尝试重现您所询问的行为?
  • edit您的问题并显示接受连接并确定并打印客户端端口号的代码。
  • 好的,我编辑了帖子
  • htons。尝试以十六进制打印它们:它们是相同的两个字节,但顺序不同。 sin_port 被记录为网络字节顺序。

标签: c sockets


【解决方案1】:

你需要对client.sin_port进行字节翻转。

printf("client connected: %s:%d\n",inet_ntoa(client.sin_addr), ntohs(client.sin_port));

34997 是 0x88B5。将这些字节的字节序翻转为 0xB588,得到 46472,如 netstat 输出所示。有关ntohs man page 的更多信息。

注意client.sin_addr 很可能是unsigned short(请参阅struct sockaddr_in 定义herehere,检查您自己的系统),但是这个will be promoted to an int,所以%d 格式说明符很好.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多