Skip to content

Instantly share code, notes, and snippets.

@Silica163
Created April 30, 2025 09:38
Show Gist options
  • Select an option

  • Save Silica163/b31eb139b5b56517d3428a47d7066f6c to your computer and use it in GitHub Desktop.

Select an option

Save Silica163/b31eb139b5b56517d3428a47d7066f6c to your computer and use it in GitHub Desktop.
#include <stdio.h> // standard in-out
#include <errno.h> // error message
#include <unistd.h> // close function
#include <string.h>
#include <sys/socket.h> // socket
#include <netinet/in.h> // network address
#include <arpa/inet.h> // convert port number
int main(int argc, char **argv){
// create socket
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0){
fprintf(stderr, "Error: Cannot create socket, %s\n", strerror(errno));
return 1;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8082);
addr.sin_addr.s_addr = INADDR_ANY;
int ret = 0;
int reuse = 1;
ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
if(ret == -1){
fprintf(stderr, "Error: Cannot set socket option, %s\n", strerror(errno));
return 1;
}
ret = bind(sock, (struct sockaddr *) &addr, sizeof(addr));
if(ret < 0){
fprintf(stderr, "Error: Couldn't bind socket, %s\n", strerror(errno));
return 1;
}
ret = listen(sock, 10);
if(ret < 0){
fprintf(stderr, "Error: Too lound, could not listen. %s\n", strerror(errno));
return 1;
}
printf("server is running at 127.0.0.1:8082\n");
while(1){
int client = accept(sock, NULL, NULL);
printf("client connected\n");
if(client < 0){
fprintf(stderr, "Error: accept: %s\n", strerror(errno));
break;
}
char buff[256] = {0};
size_t r = recv(client, buff, sizeof(buff), 0);
if(r < 0){
fprintf(stderr, "Error: recv: %s\n", strerror(errno));
break;
}
printf("RECV: %.*s", r, buff);
while(r > 0){
size_t s = send(client, buff, r, MSG_NOSIGNAL);
if(s < 0){
fprintf(stderr, "Error: send: %s\n", strerror(errno));
break;
}
r = recv(client, buff, sizeof(buff), 0);
if(r < 0){
fprintf(stderr, "Error: recv: %s\n", strerror(errno));
break;
}
if(r == 0){
break;
}
printf("RECV: %.*s", r, buff);
}
ret = shutdown(client, SHUT_RDWR);
if(ret < 0){
fprintf(stderr, "Error: shutdown: %s\n", strerror(errno));
}
close(client);
printf("client disconnected.\n");
}
shutdown(sock,SHUT_RDWR);
close(sock);
printf("exiting\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment