linux网络编程之tcp模板



/* client  */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> 


int main(int argc, char *argv[])
{

    int portnumber = 0;
    int sockfd = -1;
    struct hostent *host;
    struct sockaddr_in serveraddr;
    char buf[1024] = {0};

    if (3 != argc || 0 > (portnumber = atoi(argv[2]))){
        printf("Usage:%s hostname portnumber\n", argv[0]);
        exit(1);
    }

    if (NULL == (host = gethostbyname(argv[1]))){
        perror("gethostname error");
        exit(1);
    }
    
    if (-1 == (sockfd = socket(AF_INET, SOCK_STREAM, 0))){
        perror("socket error");
        exit(1);
    }

    bzero(&serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(portnumber);
    serveraddr.sin_addr = *((struct in_addr *)host->h_addr);

    if (-1 == connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(struct sockaddr))){
        perror("connect error:");
        exit(1);
    }

    if (-1 == read(sockfd, buf, 1024)){
        perror("recv error:");
    }
    printf("data arrived:%s\n", buf);

    close(sockfd);


    return 0;
}

/* server */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> 


int main( int argc, char *argv[])
{
    int portnumber = 0;
    int sockfd = -1;
    int clientfd = -1;
    int addrlen = 0;
    struct sockaddr_in serveraddr, clientaddr;

    if (2 != argc || 0 > (portnumber = atoi(argv[1]))){
        printf("Usage: %s port \n", argv[0]);
        exit(1);
    }
    
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sockfd){
        perror("socket error:");
        exit(1);
    }

    bzero(&serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(portnumber);
    serveraddr.sin_addr.s_addr = INADDR_ANY;

    if (-1 == bind(sockfd, (struct sockaddr *)(&serveraddr), sizeof(serveraddr))){
        perror("bind error:");
        exit (1);
    }

    if (-1 == listen(sockfd, 4)){
        perror("listen error:");
        exit(1);
    }

    while (1){
        addrlen = sizeof(struct sockaddr_in);
        if (-1 == (clientfd = accept(sockfd, (struct sockaddr*)&clientaddr, &addrlen))){
            perror("accept error");
            exit(1);
        }

            printf("connect from %s:%u ...\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
            if (-1 == write(clientfd, "hello", strlen("hello"))){
                perror("write error");
                exit(1);
            }

            close(clientfd);
    }


    close(sockfd);


    return 0;
}

原文:http://blog.chinaunix.net/uid-23069658-id-3273673.html

你可能感兴趣的:(tcp,socket)