第5章 TCP服务器-客服端程序例子

  • int inet_aton(const char *cp, struct in_addr *inp)函数将点分十进制的ip地址转换为网络的大端字节序

  • 服务端程序

#include <sys/socket.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <time.h>

#include <assert.h>
#include <iostream>
using namespace std;


int main(int argc, char** argv)
{
    time_t ticks;
    char buff[2048];
    int socket_id;
    //1 定义套接口
    socket_id = socket(AF_INET, SOCK_STREAM, 0); 
    if(socket_id < 0)
    {   
        cout << "socket failed." << endl;
        assert(-1);
    }   
    //2 给套接口绑定协议地址
    struct sockaddr_in ser_addr, cli_addr;
    bzero(&ser_addr, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    //ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    inet_aton("10.129.90.81",(in_addr*)&ser_addr.sin_addr.s_addr);
    ser_addr.sin_port = htons(1300);
    int bind_id = bind(socket_id, (struct sockaddr*)&ser_addr, sizeof(ser_addr));
    if(bind_id < 0)
    {   
        cout << "bind failed." << endl;
        assert(-1);
    }   
    //3 建立监听
    int listen_id = listen(socket_id, 1000);
    if(listen_id < 0)
    {   
        cout << "listen failed." << endl;
        assert(-1);
    }   
    //4 接受连接
    int accept_id;
    socklen_t cli_len;
    while((accept_id = accept(socket_id, (struct sockaddr*)&cli_addr, &cli_len)) > 0)
    {   
        printf("connection from %s, port %d\n", inet_ntop(AF_INET, &cli_addr.sin_addr, buff, sizeof(buff)), ntohs(cli_addr.sin_port));
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));  
        write(accept_id, buff, strlen(buff));
        close(accept_id);    
    }   
    return 0;
}
  • 客服端程序
#include <sys/socket.h> 
#include <stdlib.h> 
#include <arpa/inet.h> 
#include <string.h> 
#include <stdio.h> 

#include <assert.h> 
#include <iostream> 
using namespace std;    


int main(int argc, char** argv)    
{    
    int socket_id;    
    //1 定义套接口 
    socket_id = socket(AF_INET, SOCK_STREAM, 0);    
    if(socket_id < 0)    
    {    
        cout << "socket failed." << endl;    
        assert(-1);    
    }    
    struct sockaddr_in ser_addr;    
    bzero(&ser_addr, sizeof(ser_addr));    
    ser_addr.sin_family = AF_INET;    
    //ser_addr.sin_addr.s_addr = htonl(INADDR_ANY); 
    inet_aton("10.129.90.81",(in_addr*)&ser_addr.sin_addr.s_addr);
    ser_addr.sin_port = htons(1300);    
    connect(socket_id, (struct sockaddr*)&ser_addr, sizeof(ser_addr));
    int n;
    char line[2048];
    while((n = read(socket_id, line, 2048)) > 0)
    {   
        line[n] = 0;
        printf("%s\n", line);
    }   
    return 0;
}

你可能感兴趣的:(unix网络编程)