linux网络编程,listen和connect

listentest.c
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MYPORT 3490
#define BACKLOG 10


main()
{
        int sockfd,new_fd;
        struct sockaddr_in my_addr;
        struct sockaddr_in their_addr;
        int sin_size;

        sockfd = socket(AF_INET,SOCK_STREAM,0);
        my_addr.sin_family=AF_INET;
        my_addr.sin_port=htons(MYPORT);
        my_addr.sin_addr.s_addr=htonl(INADDR_ANY);
        bzero(&(my_addr.sin_zero),8);
        bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr));

        listen(sockfd,BACKLOG);
        while(1)
        {
                sin_size=sizeof(struct sockaddr_in);
                new_fd=accept(sockfd,&their_addr,&sin_size);

                printf("get connected:/n");
                printf("client IP adress:%s/n",inet_ntoa(their_addr.sin_addr));
                printf("    port  : %d/n",their_addr.sin_port);
        }
        exit(0);
}

connecttest.c
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define DEST_IP "127.0.0.1"
#define DEST_PORT 3490

main()
{
        int sockfd;
        struct sockaddr_in dest_addr;
        sockfd=socket(AF_INET,SOCK_STREAM,0);

        dest_addr.sin_family=AF_INET;
        dest_addr.sin_port=htons(DEST_PORT);
        dest_addr.sin_addr.s_addr=inet_addr(DEST_IP);
        bzero(&(dest_addr.sin_zero),8);

        int ret=connect(sockfd,(struct sockaddr *)&dest_addr,sizeof(struct sockaddr));
        if(ret==-1)
        {
                printf("error linking");
                exit(0);
        }

        exit(0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值