求帮助各位高手,C写程序来判断某端口能否被占用该怎么写
解决方案
15
int port = 8888; int fd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr); if(bind(fd, (struct sockaddr *)(&addr), sizeof(sockaddr_in)) < 0) { printf("port %d has been used.\n", port); } close(fd);
15
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #define MAXLINE 80 int main(void) { struct sockaddr_in servaddr; int sockfd,i,serverport,ret; sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr); for(i = 0;i < 65535;i++) { servaddr.sin_port = htons(i); ret = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); if(EISCONN == ret) { printf("端口 %d被占用",i); } else { close(sockfd); } } return 0; }
10
system("netstat -na >netstat.txt"); //然后读文件netstat.txt的内容