linux网络编程tcp

天大地大妈咪最大 提交于 2020-04-04 15:20:57

之前学习的时候笔记没有保存好,这次重新编写一个案例。

客户端实现程序代码:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>


#define DEF_TCP_SRV_PORT 19868

int main()
{

    struct sockaddr_in addr;
    struct sockaddr_in srv_addr;
    int net_sock;
    int new_fd;

    int res;
    int len;

    char buff[128];

    // 1. socket 初始化
    // 1.1 创建socket
    net_sock = socket(AF_INET,SOCK_STREAM,0);
    if( -1 == net_sock )
    {
     printf("create socket error!\r\n");
     return -1;
    }
    // 1.2 初始化地址
    bzero( &addr, sizeof(struct sockaddr_in));

    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(DEF_TCP_SRV_PORT);

    // 1.3 bind地址
    bind( net_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));

    //监听
    listen( net_sock, 5 );

    len = sizeof(struct sockaddr);
    new_fd = accept( net_sock, (struct sockaddr *)(&srv_addr),&len );

    printf("server ip:%s\r\n",inet_ntoa(srv_addr.sin_addr));

    res = recv(new_fd, buff,125,0);
    buff[res] ='\0';

    printf("get : %s\r\n",buff);

    close(net_sock);

    return 0;
};

服务端程序代码:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>


#define DEF_TCP_SRV_PORT 19868

int main()
{
    struct sockaddr_in srv_addr;
    int sock;
    int res;
    char buff[128];

    //创建套接字
    sock = socket(AF_INET,SOCK_STREAM,0);

    if( -1 == sock )
    {
        printf("create sock failed\r\n");
        return -1;
    }

    //设置要绑定的地址
    bzero( &srv_addr, sizeof(struct sockaddr_in));

    srv_addr.sin_addr.s_addr = inet_addr("192.168.1.21");
    srv_addr.sin_family = AF_INET;
    srv_addr.sin_port = htons(DEF_TCP_SRV_PORT);

    //连接
    res = connect(sock,(struct sockaddr *)(&srv_addr),sizeof(struct sockaddr));

    if( -1==res)
    {
        printf("connect failed\r\n");
        return -1;
    }

    printf("please input data:\r\n");
    fgets(buff,128,stdin);
    //发送数据
    send( sock, buff, strlen(buff),0);

    close(sock);

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!