码迷,mamicode.com
首页 > 系统相关 > 详细

linux网络编程tcp

时间:2016-12-08 23:53:27      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:close   list   pre   char   std   accept   没有   监听   linux网络编程   

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

客户端实现程序代码:

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

}

 

linux网络编程tcp

标签:close   list   pre   char   std   accept   没有   监听   linux网络编程   

原文地址:http://www.cnblogs.com/ynxf/p/6146540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!