Skip to content

Instantly share code, notes, and snippets.

@Ehsan-hsr
Created January 15, 2022 17:06
Show Gist options
  • Save Ehsan-hsr/cbb0eb167656ed5e14845262dfe85154 to your computer and use it in GitHub Desktop.
Save Ehsan-hsr/cbb0eb167656ed5e14845262dfe85154 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
int main(){
int sockfd, newSockfd;
struct sockaddr_in serv_addr, cli_addr;
int port_number = 8888;
//create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
printf("socket failed\n");
return 1;
}
printf("socket created successfully\n");
//Prepare the sockaddr_in structur
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port_number);
//Bind
if(bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("bind failed\n");
return 1;
}
//Listen
listen(sockfd , 3);
//Accept the connectin
int c = sizeof(struct sockaddr_in);
newSockfd = accept(sockfd, (struct sockaddr *)&cli_addr, (socklen_t *)&c);
if(newSockfd < 0)
{
printf("Connection Failed\n");
return 1;
}
printf("Connection accepted");
char *msg = "Hello Client , I have received your connection\n";
//send some message to client
write(newSockfd, msg, strlen(msg));
//close socket
close(newSockfd);
close(sockfd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment