linux TCP客户端指定端口号连接服务端

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);

}

}

转载于:https://www.cnblogs.com/Dennis-mi/articles/6593007.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值