What Is Socket Programming
What Is Socket Programming
https://www.geeksforgeeks.org/socket-programming-cc/
1. Socket Creation
2. Setsockopt
This helps in manipulating options for the socket referred by the file descriptor
sockfd. This is completely optional, but it helps in reuse of address and port.
Prevents error such as: “address already in use”.
int setsockopt(int sockfd, int level, int optname, const
void *optval, socklen_t optlen);
3. Bind
4. Listen
5. Accept
Implementation
Here we are exchanging one hello message between server and client to
demonstrate the client/server model.
Server.c
C
client.c
C
// Client side C program to demonstrate Socket
// programming
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 8080
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if ((status
= connect(client_fd, (struct sockaddr*)&serv_addr,
sizeof(serv_addr)))
< 0) {
printf("\nConnection Failed \n");
return -1;
}
send(client_fd, hello, strlen(hello), 0);
printf("Hello message sent\n");
valread = read(client_fd, buffer,
1024 - 1); // subtract 1 for the null
// terminator at the end
printf("%s\n", buffer);
Output
Client:Hello message sent
Hello from server
Server:Hello from client
Hello message sent
Compiling
gcc client.c -o client
gcc server.c -o server