Linux下面貌似没有什么直接开启或者关闭端口的命令,因为若仅仅只是开启了端口而不把它与进程相联系的话,端口的开启与关闭就显得毫无意义了(开了端口却没有程序处理进来的数据)。也就是说,Linux里面端口的活动与进程是紧密相连的,如果想要关闭某个端口,那么只要杀掉它对应的进程就可以了。
www.2cto.com
客户端代码
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);
}
}