Skip to content

Instantly share code, notes, and snippets.

@tiebingzhang
Created June 7, 2019 20:02
Show Gist options
  • Save tiebingzhang/555cd1558702c429df49572a1db9ec25 to your computer and use it in GitHub Desktop.
Save tiebingzhang/555cd1558702c429df49572a1db9ec25 to your computer and use it in GitHub Desktop.
A basic tcp server in C
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#define PORT 8080
// Driver function
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(-1);
}
int flag=1;
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) == -1) {
printf("Setsockopt SO_REUSEPORT failed with errno %d\n", errno);
exit(-1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
servaddr.sin_port = htons(PORT);
if ((bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(-1);
}
while(1){
if ((listen(sockfd, 1)) != 0) {
printf("Listen failed...\n");
exit(-1);
}
printf("listening on port %d\n",PORT);
socklen_t len = sizeof(cli);
connfd = accept(sockfd, (struct sockaddr*)&cli, &len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(-1);
}
printf("server acccept the client...\n");
write(connfd,"you got it\n",11);
close(connfd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment