[国嵌攻略][091][TCP网络程序设计]

server.c

#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>

#define SERVER_PORT 3333

void main(){
     //创建标识
    int serverfd;
    
    serverfd = socket(AF_INET, SOCK_STREAM, 0);   //建立TCP连接
    
    //绑定地址
    struct sockaddr_in serverAddr;
    
    serverAddr.sin_family = AF_INET;                   //设置协议
    serverAddr.sin_port = htons(SERVER_PORT);          //设置端口
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);    //设置地址
    bzero(serverAddr.sin_zero, 8);                     //设置为零
    
    bind(serverfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr));
    
    //监听端口
    listen(serverfd, 1);
    
    //等待连接
    socklen_t clientAddrLen;
    struct sockaddr_in clientAddr;
    int clientfd;

    clientAddrLen = sizeof(struct sockaddr);
    clientfd = accept(serverfd, (struct sockaddr *)&clientAddr, &clientAddrLen);
    
    //接收数据
    char buffer[2048];
    
    recv(clientfd, buffer, sizeof(buffer), 0);
    
    //显示数据
    char *clientIPAddr;
    
    clientIPAddr = (char *)inet_ntoa(clientAddr.sin_addr.s_addr);
    printf("server recvice from %s:\n%s", clientIPAddr, buffer);

    //关闭连接
    close(clientfd);
    close(serverfd);
}

 

client.c

#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>

#define SERVER_PORT 3333

int main(int argc, char **argv){
    //参数检查
    if(argc != 2){
        printf("Usage:\n\t./client <ip address>\n");
        return -1;
    }
    
    //创建标识
    int clientfd;
    
    clientfd = socket(AF_INET, SOCK_STREAM, 0);   //建立TCP连接
    
    //建立连接
    struct sockaddr_in serverAddr;
    
    serverAddr.sin_family = AF_INET;                   //设置协议
    serverAddr.sin_port = htons(SERVER_PORT);          //设置端口
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);   //设置地址
    bzero(serverAddr.sin_zero, 8);                     //设置为零
    
    connect(clientfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr));

    //输入数据
    char buffer[2048];
    
    printf("client send to %s:\n", argv[1]);
    fgets(buffer, sizeof(buffer), stdin);
    
    //发送数据
    send(clientfd, buffer, sizeof(buffer), 0);
    
    //关闭连接
    close(clientfd);
    
    return 0;
}

 

posted @ 2016-03-01 20:08  盛夏夜  阅读(308)  评论(0编辑  收藏  举报