Hey,
I'm new to Socket Programming, and i've only learned C recently so probably what i'm asking will be very obvious, sorry in advance (=
ok Here's my code
/*
* File: Inside_Client.c
* Author: Ghaith Hachem and Adel Youssef
*
* Created on March 17, 2008, 6:12 AM
*/
#define EXIT_SUCCESS 0
#define PORT 1234
#define IP "192.168.0.1"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
/*
*
*/
//Variable Definitions
//Hostname will be used later with gethostbyname(), i kept an example below
//char hostname[100];
char *msg;
int sockfd;
struct sockaddr_in server_addr;
bool Connected;
//Was used in gethostbyname();
//struct hostent *hp;
int main(int argc, char** argv) {
/*
*This is the gethostbyname example
strcpy(hostname,HOST);
if (argc>2)
{ strcpy(hostname,argv[2]); }
if ((hp = gethostbyname(hostname)) == 0) {
perror("gethostbyname");
exit(1);
*/
//Define default options
memset (&server_addr, '\0', sizeof (server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(IP);
//Create the Socket
if (sockfd = socket(PF_INET, SOCK_STREAM, 0) < 0) {
perror("Could not create socket");
exit(1);
};
//Connect
if (connect(sockfd,(struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
{
perror("Cannot connect to server");
exit(2);
};
printf("Connected to host");
//Authenticating message for now is "Hello"
msg = "Hello";
//Send authentication message
if (send(sockfd, msg, strlen(msg), 0) < 0)
{
perror("Failed to send authentication");
exit(3);
};
Connected = true;
while(Connected)
{
if (recv(sockfd,msg,strlen(msg), 0) < 0)
{
perror("Failed to receive messages, shutting down");
Connected = false;
};
//Handle received messages here, for now just print out the message
printf("%s\n", msg);
};
close(sockfd);
return (EXIT_SUCCESS);
}
I'm getting
Socket operation on non-socket on the connect() statement, i did a little trace and found out that sockfd was set to 0 at the time, which will explain the error i suppose, but i'm not sure how it got to 0, what have i done wrong?
thank you