Hey all
I'm trying to write an application (simple TCP Server) that uses sockets. I'm using XCode. I'm unable to get my socket to bind to an address. I've posted my code... does anyone see any mistakes?
The app returns an error when I use the bind command... but I can't figure out why.
TiA
-Preet
I'm trying to write an application (simple TCP Server) that uses sockets. I'm using XCode. I'm unable to get my socket to bind to an address. I've posted my code... does anyone see any mistakes?
The app returns an error when I use the bind command... but I can't figure out why.
Code:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 80
int main (int argc, const char * argv[])
{
//____________________________________________
// Create the server socket
//create socket
int dataRx;
dataRx = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
//error checking
if ( dataRx < 0 )
{
printf("\nerror -> Could not create socket");
printf("\nExiting...");
//sleep (3);
return 0;
}
else {
printf("\n->Created server socket"); }
//____________________________________________
// Get local machine (server) address info
char myName [256];
struct sockaddr_in local;
struct hostent *hp;
//get local host info
gethostname (myName, sizeof(myName));
printf("\n->This machine's hostname is: %s", myName);
hp = gethostbyname (myName);
if (hp == NULL)
{
printf("\nerror -> Could not get local host info");
printf("\nExiting...");
return 0;
}
else {
printf("\n->Got local host info"); }
//fill in info
local.sin_family = AF_INET;
local.sin_port = htons (80);
local.sin_addr.s_addr = htonl (INADDR_ANY);
//____________________________________________
// Bind socket to address
int errCh = 0;
errCh = bind (dataRx, (struct sockaddr*)&local, sizeof(local) );
if (errCh < 0)
{
printf("\nerror -> Could not bind socket to address");
printf("\n %d", errCh);
printf("\nExiting...");
return 0;
}
else {
printf("\n->Socket bound to local address"); }
//____________________________________________
// Start listening for connections
getchar();
return 0;
}
TiA
-Preet