Linux c 根据socket套接字获取当前监听的端口
1 struct sockaddr_in localaddr; 2 ///一定要给出结构体大小,要不然获取到的端口号可能是0 3 socklen_t len = sizeof(localaddr);
///fd是创建的套接字 4 int ret = getsockname(fd, (struct sockaddr*)&localaddr, &len); 5 6 if(ret != 0) 7 { 8 perror("getsockname"); 9 } 10 else 11 { 12 perror("getsockname"); 13 printf("port: %d\n", ntohs(localaddr.sin_port)); 14 }