获得server的port

先listen,然后获得端口

 1 #include<unistd.h>
 2 #include<stdio.h>
 3 #include<unistd.h>
 4 #include<string.h>
 5 #include<signal.h>
 6 #include <sys/stat.h>
 7 #include <sys/types.h>
 8 #include<fcntl.h>
 9 #include <dlfcn.h>
10 #include <errno.h>
11 #include <error.h>
12 #include <stdlib.h>
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 int main(int argc, const char *argv[])
16 {
17     struct sockaddr_in my_addr;
18     int sockfd;
19     int flag;
20     int len=sizeof(struct sockaddr);
21 
22 
23     if ((sockfd=socket(PF_INET,SOCK_STREAM,0))<0) {
24         printf("initmasterserver failed\n");
25     exit(1);
26     }
27     listen(sockfd,20);
28     flag=getsockname(sockfd,(struct sockaddr *)&my_addr,&len);
29     if (flag) {
30         perror("");
31         printf("error\n");
32     }
33     printf("%d\n",htons(my_addr.sin_port));
34 
35     while(1)
36     {
37         sleep(10);
38     }
39     return 0;
40 }
原文地址:https://www.cnblogs.com/mengqingzhong/p/3033965.html