Skip to content

Instantly share code, notes, and snippets.

@inaz2
Created March 4, 2016 08:20
Show Gist options
  • Save inaz2/0e77c276a834ad8e3131 to your computer and use it in GitHub Desktop.
Save inaz2/0e77c276a834ad8e3131 to your computer and use it in GitHub Desktop.
IPv6 server & client in C
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
void ping(int s, char *message)
{
char buf[8192];
strncpy(buf, message, sizeof(buf));
send(s, buf, strlen(buf), 0);
recv(s, buf, 8192, 0);
strtok(buf, "\n");
puts(buf);
}
int main()
{
int s;
struct sockaddr_in6 addr;
s = socket(AF_INET6, SOCK_STREAM, 0);
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(5000);
inet_pton(AF_INET6, "::1", &addr.sin6_addr);
connect(s, (struct sockaddr *)&addr, sizeof(addr));
ping(s, "hoge\n");
ping(s, "fuga\n");
ping(s, "piyo\n");
close(s);
return 0;
}
$ gcc server.c -o server
$ gcc client.c -o client
$ ./server &
[1] 6422
$ netstat -ant
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:6010 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
tcp 0 216 192.168.56.2:22 192.168.56.1:54688 ESTABLISHED
tcp 0 0 192.168.56.2:22 192.168.56.1:59121 ESTABLISHED
tcp6 0 0 :::22 :::* LISTEN
tcp6 0 0 ::1:6010 :::* LISTEN
tcp6 0 0 ::1:6011 :::* LISTEN
tcp6 0 0 :::5000 :::* LISTEN
$ ./client
hoge
fuga
piyo
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
void handle_client(int c)
{
char buf[8192];
char *lastpos;
int size;
while (1) {
size = recv(c, buf, 8192, 0);
if (size == 0) {
break;
}
lastpos = strchr(buf, '\n');
send(c, buf, lastpos+1-buf, 0);
}
}
int main()
{
int s, c;
int reuseaddr = 1;
struct sockaddr_in6 addr;
int pid;
s = socket(AF_INET6, SOCK_STREAM, 0);
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(5000);
addr.sin6_addr = in6addr_any;
bind(s, (struct sockaddr *)&addr, sizeof(addr));
listen(s, 5);
while (1) {
c = accept(s, NULL, NULL);
pid = fork();
if (pid == -1) {
exit(1);
} else if (pid == 0) {
close(s);
handle_client(c);
close(c);
return 0;
} else {
close(c);
waitpid(pid, NULL, 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment