簡単なTCPサービスとクライアントのC実現


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc , char *argv[]) {
    //socket   
    char receive_message[256] = {};
    char message[] = {"Hi, I am server."};
    int s_sockfd = 0, c_sockfd = 0;
    s_sockfd = socket(AF_INET , SOCK_STREAM , 0);

    if (s_sockfd == -1) {
        printf("Fail to create a socket.");
    }

    //              
    int opt;
    setsockopt(s_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    //socket   
    struct sockaddr_in s_addr, c_addr;
    int addrlen = sizeof(struct sockaddr_in);
    bzero(&s_addr, sizeof(struct sockaddr_in));

    s_addr.sin_family = AF_INET;
    s_addr.sin_addr.s_addr = inet_addr("127.0.0.1");//or INADDR_ANY
    s_addr.sin_port = htons(30003);
    if (bind(s_sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr)) == -1) {
        printf("bind() failed!");
        exit(0);
    }
    if (listen(s_sockfd, 5) == -1) {
        printf("listen() failed!");
        exit(0);
    }

    while (1) {
        c_sockfd = accept(s_sockfd, (struct sockaddr*) &c_addr, (socklen_t *)&addrlen);
        int s = send(c_sockfd, message, sizeof(message), 0);
        if (s == -1) printf("send data failed
"
); int r = recv(c_sockfd, receive_message, sizeof(receive_message), 0); if (r == -1) printf("receive data failed
"
); printf("received=%s
"
, receive_message); printf("send data size=%d, receive data size=%d
"
, s, r); } return 0; }
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

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

    //socket   
    int sockfd = 0;
    sockfd = socket(AF_INET , SOCK_STREAM , 0);

    if (sockfd == -1) {
        printf("Fail to create a socket.");
    }

    //socket   
    struct sockaddr_in info;
    bzero(&info, sizeof(info));
    info.sin_family = AF_INET;
    info.sin_addr.s_addr = inet_addr("127.0.0.1");//or INADDR_ANY
    info.sin_port = htons(30003);

    int err = connect(sockfd, (struct sockaddr *)&info, sizeof(info));
    if (err == -1) {
        printf("Connection error
"
); } //Send and receive a message char message[] = {"Hi, I am client."}; char receive_message[100] = {}; int s = send(sockfd, message, sizeof(message), 0); if (s == -1) printf("send data failed
"
); int r = recv(sockfd, receive_message, sizeof(receive_message), 0); if (r == -1) printf("receive data failed
"
); printf("received=%s
"
, receive_message); printf("send data size=%d, receive data size=%d
"
, s, r); printf("close Socket
"
); close(sockfd); return 0; }