Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@medaka5

Socketプログラムメモ: printfとcloseするだけのサーバー作ってみた

More than 5 years have passed since last update.

ログ出力だけしてcloseするサーバー。
telnet localhost 12345で試せます。
wiresharkでlocalhostを観察しながら勉強しました。
もしくは、sudo tcpdump -n -i lo0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int listenfd, connfd;
    struct sockaddr_in servaddr;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if(listenfd < 0) {
        perror("socket() err");
        exit(EXIT_FAILURE);
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(12345);
    servaddr.sin_len = sizeof(servaddr);

    if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
        perror("bind() err");
        exit(EXIT_FAILURE);
    }

    if(listen(listenfd, SOMAXCONN) < 0) {
        perror("listen() err");
        exit(EXIT_FAILURE);
    }
    for(;;) {
        connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
        if(connfd < 0) {
            perror("accept() err");
            exit(EXIT_FAILURE);
        }
        printf("----\n");
        if(close(connfd) == -1) {
            perror("close() err");
            exit(EXIT_FAILURE);
        }
    }
    return 0;
}
2
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
medaka5

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
2
Help us understand the problem. What is going on with this article?