tcp协议 编程实例

====================server.c===================

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#define MAXLINE 50
typedef struct sockaddr SA;

int main(int argc, char **argv)
{
        int listenfd,connfd;
        socklen_t clilen;
        struct sockaddr_in myaddr,cliaddr;
        char buf[MAXLINE]="welcome to TCP server";

        if((listenfd = socket(PF_INET,SOCK_STREAM,0))<0)       //创建套接字
        {
                perror("fail to socket");
                exit(-1);
        }
        bzero(&myaddr,sizeof(myaddr));
        myaddr.sin_family       =PF_INET;
        myaddr.sin_addr.s_addr  =inet_addr("192.168.0.21");
        myaddr.sin_port         =htons(8888);
 

        if(bind(listenfd,(SA*)&myaddr,sizeof(myaddr))<0)          //绑定
        {
                perror("fail to bind");
                exit(-1);
        }
        listen(listenfd,5);//监听

        while(1)
        {
                clilen  = sizeof(cliaddr);
                connfd  = accept(listenfd,(SA*)&cliaddr,&clilen);//等待接收链接
                printf("connection from %s,port %d/n",
                                inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
                if(send(connfd,buf,sizeof(buf),0)<0)//发送
                {
                printf("send failed");
                break;
                }
                close(connfd);
        }
        return 0;
}

 

 

 

==================client.c===================

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#define MAXLINE 50
typedef struct sockaddr SA;

int main(int argc, char **argv)
{
        int sockfd,nbyte;
        struct sockaddr_in servaddr,myaddr;
        char buf[MAXLINE];

        if((sockfd = socket(PF_INET,SOCK_STREAM,0))<0)   //创建套接字
        {
                perror("fail to socket");
                exit(-1);
        }
        bzero(&servaddr,sizeof(servaddr));//清零
        servaddr.sin_family     =PF_INET;
        servaddr.sin_addr.s_addr        =inet_addr("192.168.0.21");
        servaddr.sin_port               =htons(8888);
        if(connect(sockfd,(SA*)&servaddr,sizeof(servaddr))<0)   //链接
        {
                perror("fail to connect");
                exit(-1);
        }

        if((nbyte = recv(sockfd,buf,MAXLINE,0))<0)//接收
        {
                perror("fail to recv");
                exit(-1);
        }

        printf("recv from server:%s",buf);
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值