Linux下面貌似没有什么直接开启或者关闭端口的命令,因为若仅仅只是开启了端口而不把它与进程相联系的话,端口的开启与关闭就显得毫无意义了(开了端口却没有程序处理进来的数据)。也就是说,Linux里面端口的活动与进程是紧密相连的,如果想要关闭某个端口,那么只要杀掉它对应的进程就可以了。
客户端代码
- #include <stdio.h>
- #include <stdlib.h>
- #include <strings.h>
- #include <arpa/inet.h>
- #include <sys/socket.h>
- int main(){
- int sockfd = socket(AF_INET,SOCK_STREAM,0);
- if(sockfd==-1)perror("sock");
- struct sockaddr_in mine,dest;
-
- bzero(&mine,sizeof(mine));
- mine.sin_family = AF_INET;
- mine.sin_port = htons(3334);
- inet_pton(AF_INET,"192.168.1.100",&mine.sin_addr);
-
- bzero(&dest,sizeof(dest));
- dest.sin_family = AF_INET;
- dest.sin_port = htons(9999);
- inet_pton(AF_INET,"192.168.1.100",&dest.sin_addr);
- int b = bind(sockfd,(struct sockaddr*)&mine,sizeof(mine));
- if(b==-1)perror("");
-
- int c = connect(sockfd,(struct sockaddr*)&dest,sizeof(dest));
- if(c!=0)perror("");
- close(sockfd);
-
- }
服务端代码
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <strings.h>
- int main(){
- int sockfd = socket(AF_INET,SOCK_STREAM,0);
- struct sockaddr_in addr;
- bzero(&addr,sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_port = htons(9999);
- inet_pton(AF_INET,"192.168.1.100",&addr.sin_addr);
- bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
- listen(sockfd,5);
- while(1){
- struct sockaddr_in c_addr;
- int c_len = sizeof(c_addr);
- bzero(&c_addr,c_len);
- int c = accept(sockfd,(struct sockaddr*)&addr,&c_len);
- if(c==-1)perror("");
- char ip[40]={0};
- int port;
- inet_ntop(AF_INET,&addr.sin_addr,ip,40);
- port = ntohs(addr.sin_port);
- printf("from %s:%d\n",ip,port);
- close(c);
- }
- }
建立连接后用
netstat -anp|grep 端口号查看端口状态及进程号
若想关闭端口连接 ,使用kill -9 进程号关闭
-a 显示所有活动的TCP连接,以及正在监听的TCP和UDP端口
-n 以数字形式表示地址和端口号N
-p 列出与端口监听或连接相关的进程
netstat -tuln 列出所有inet地址类的端口监听状态
netstat -tn 列出所有TCP协议的连接状态
阅读(1592) | 评论(0) | 转发(0) |