linux socket编程一:TCP客户端、服务端简单实例

//server端代码

#include <stdio.h>

//#include <linux/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
    int fd,ret;
    struct sockaddr_in addr = {0};
    fd = socket(AF_INET,SOCK_STREAM,0);
    if(-1 == fd)
    {
        printf("error:%s\n",strerror(errno));
        return fd;
    }
    addr.sin_family = AF_INET;
    addr.sin_port = htons(2000);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    ret = bind(fd,(struct sockaddr *)(&addr),sizeof(struct sockaddr));
    if(-1 == ret)
    {
        printf("error:%s\n",strerror(errno));
        return ret;
    }
    int yes = 1;
    ret = setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes));
    if(-1 == ret)
    {
        printf("error:%s\n",strerror(errno));
        return ret;
    }
    ret = listen(fd,5);
    if(-1 == ret)
    {
        printf("error:%s\n",strerror(errno));
        return ret;
    }
    while(1)
    {
    socklen_t len = sizeof(addr);
    int cd = accept(fd,(struct sockaddr*)(&addr),&len);
    if(-1 == cd)
    {
        printf("error:%s\n",strerror(errno));
        return cd;
    }
    printf("connected from %s:%d\n",inet_ntoa(addr.sin_addr),addr.sin_port);
    char buf[100] = {0};
    time_t t = time(NULL);
    strcpy(buf,ctime(&t));
    ret = send(cd,buf,strlen(buf),0);
    if(-1 == ret)
    {
        printf("error:%s\n",strerror(errno));
        return ret;
    }
    printf("size %d of %d sent\n",ret,strlen(buf));
    close(cd);
    }

}

//客户端代码

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
    int fd,ret;
    struct sockaddr_in addr = {0};
    struct in_addr x;
    inet_aton("192.168.1.103",&x);
    addr.sin_family = AF_INET;
    addr.sin_addr = x;
    addr.sin_port = htons(2000);
    fd = socket(AF_INET,SOCK_STREAM,0);
    if(fd == -1)
    {
        printf("error:%s\n",strerror(errno));
        return fd;
    }
    ret = connect(fd,(sockaddr*)&addr,sizeof(addr));
    if(ret == -1)
    {
        printf("error:%s\n",strerror(errno));
        return fd;
    }
    char buf[100]={0};
    ret = recv(fd,buf,sizeof(buf),0);
    if(ret == -1)
    {
        printf("error:%s\n",strerror(errno));
        return fd;
    }
    write(STDOUT_FILENO,buf,ret);
    close(fd);
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值