Essentially I have a server that will be listening for sockets in other programs seeking a connection:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <linux/netdevice.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_LEN 80
int main(int argc, char *argv[]){
int recvSocket, serverSocket;
char buffer[1024];
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
char user[MAX_LEN];
char pass[MAX_LEN];
char name[MAX_LEN];
char port[MAX_LEN];
struct iovec iov[2];
struct ifconf ifconf;
struct ifreq ifr[50];
if (2 != argc) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
/*---- Create the socket. The three arguments are: ----*/
/* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
recvSocket = socket(PF_INET, SOCK_STREAM, 0);
ifconf.ifc_buf = (char *) ifr;
ifconf.ifc_len = sizeof ifr;
if (ioctl(recvSocket, SIOCGIFCONF, &ifconf) == -1) {
perror("ioctl");
return 0;
}
char ip[INET_ADDRSTRLEN];
struct sockaddr_in *s_in = (struct sockaddr_in *) &ifr[1].ifr_addr;
if (!inet_ntop(AF_INET, &s_in->sin_addr, ip, sizeof(ip))) {
perror("inet_ntop");
return 0;
}
/*---- Configure settings of the server address struct ----*/
/* Address family = Internet */
serverAddr.sin_family = AF_INET;
/* Set port number, using htons function to use proper byte order */
serverAddr.sin_port = htons(atoi(argv[1]));
/* Set IP address to localhost */
serverAddr.sin_addr.s_addr = inet_addr(ip);
/* Set all bits of the padding field to 0 */
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
/*---- Bind the address struct to the socket ----*/
bind(recvSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
if(listen(recvSocket,5)==0)
printf("Listening\n");
else
printf("Error\n");
/*---- Accept call creates a new socket for the incoming connection ----*/
addr_size = sizeof serverStorage;
serverSocket = accept(recvSocket, (struct sockaddr *) &serverStorage, &addr_size);
Here, I am trying to get the IP of the computer in order to set it up the socket on this program. Later on, a client will be connecting to it, where it will be given the same address by the user (so no worries on that side).
It seems to work just fine, but I get the feeling I am doing extra steps that could be simplified. Does anyone have any idea if it could be so? I guided myself from this question and this article to create mine.