Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netdb.h>
- #include <unistd.h>
- #define MSG_SIZE 1024
- #define LISTEN_Q 32
- struct sockFDList {
- int sockFD;
- struct sockFDList *next;
- };
- int main(int argc, char *argv[]) {
- int listenFD, newFD, fdmax, i; // listenFD for listening, newFD for new connection
- char msg[MSG_SIZE]; // buffer for msg transmit
- struct addrinfo hints, *myAI; // address info
- struct sockaddr_storage remoteAddr; // store client address
- socklen_t sizeAddr; // sizeof client address
- fd_set masterSet, readSet; // FD sets for list and read.
- // Clear Sets
- FD_ZERO(&masterSet);
- FD_ZERO(&readSet);
- // Clear hints
- memset(&hints, 0, sizeof hints);
- // Prep hints
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags = AI_PASSIVE;
- // Get local addr info
- getaddrinfo("localhost", argv[1], &hints, &myAI);
- // Get socket for listening
- listenFD = socket(myAI->ai_family, myAI->ai_socktype, myAI->ai_protocol);
- // Bind socket sockFD
- bind(listenFD, myAI->ai_addr, myAI->ai_addrlen);
- // Add sfd to master set
- FD_SET(listenFD, &masterSet);
- // Initialize fdmax
- fdmax = listenFD;
- while(1) {
- // Copy master
- readSet = masterSet;
- // call select
- if(select(fdmax+1, &readSet, NULL, NULL, NULL) == -1)
- continue;
- // loop through readSet
- for(i=0; i<=fdmax; i++) {
- if(FD_ISSET(i, &readSet)) { // Active !
- if(i == listenFD) { // If listener socket
- // New Connection, accept
- sizeAddr = sizeof remoteAddr;
- newFD = accept(listenFD, (struct sockaddr *)&remoteAddr, &sizeAddr);
- printf("\n");
- // Add this connection to my master list
- FD_SET(newFD, &masterSet);
- // update fdmax
- if(newFD > fdmax)
- fdmax = newFD;
- }
- else {
- // Something to read on a socket
- recv(i, msg, MSG_SIZE, 0);
- msg[MSG_SIZE] = '\0';
- // print it.
- printf("%s\n",msg);
- }
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement