Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions server.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 8080
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#include が全部終わった後には空行をおきたい。

#define BUFFER_SIZE 1024
int main(int argc, char const* argv[])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

関数が始まる前にも空行をおきたい。

{
int server_socket, new_socket;
char* message = "I'm server";
struct sockaddr_in server_address;
int option = 1;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sockopt とか socket_option とかの名前にしたい。

char buffer[BUFFER_SIZE] = {0};


server_socket = socket(AF_INET, SOCK_STREAM, 0);
if(server_socket < 0){
perror("Socket Error");
exit(1);
}


if(setsocketopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0){
perror("Can't set option");
exit(1);
}
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コマンドライン引数でアドレス・ポートを指定できるようにしたい。

server_address.sin_port = htons(PORT);

if(bind(server_socket, (struct sockadd*)&server_address, sizeof(server_address)) < 0){
perror("Can't bind");
exit(1);
}

if(listen(server_socket, SOMAXCONN) < 0){
perror("Can't listen");
exit(1);
}

new_socket = accept(server_socket, (struct sockadd*)&server_address, sizeof(server_address));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

accept の第3引数はint * をうけるので、書き込み可能な変数のアドレスを渡す。

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

accept をループで回すようにしたい。(複数のクライアントを処理する)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2,3 引数は client_address に関連する sockaddr

if(new_socket < 0){
perror("Can't bind");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bind じゃない

exit(1);
}


read(new_socket, buffer, BUFFER_SIZE-1)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

read は一発で読めないことがあるので、それの対応をする。

printf("%s\n", buffer, );
close();
printf("message sent\n");
close();



return 0;
}