Advertisement

c socket programming

Started by January 14, 2005 10:54 AM
4 comments, last by Genjix 19 years, 8 months ago
Im trying to do some socket programming, but listen seems to fail.

/*standard headers*/
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

/*socket headers*/
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/*types*/
#include <signal.h>
#include <sys/types.h>

void exit_err(const char *error_msg)
{
	fputs(error_msg,stderr);
	exit(-1);
}

int main()
{
	int fd_sock , new_fd;
	struct sockaddr_in my_addr , their_addr;

	int sin_size;
	struct sigaction sa;
	int yes = 1;
 
	if((fd_sock = socket(AF_INET,SOCK_DGRAM,0)) < 0)
		exit_err("error in fd\n");

	if(setsockopt(fd_sock , SOL_SOCKET , SO_REUSEADDR , &yes , sizeof(int)) < 0)
		exit_err("error in sockopt\n");

	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(4829);
	my_addr.sin_addr.s_addr = INADDR_ANY;
	bzero(&(my_addr.sin_zero),8);

	if(bind(fd_sock , (struct sockaddr*)&my_addr , sizeof(struct sockaddr)) < 0)
		exit_err("errir in bind\n");

	if(listen(fd_sock,10) < 0)
		exit_err("error listening\n");

	return 0;
}

Add #include <errno.h> to the top and see what errno is set to. I get an EOPNOTSUPP error when I run the code.

It looks like your socket is a SOCK_DGRAM, but my man page for listen() says it will only work on SOCK_STREAM and SOCK_SEQPACKET sockets.
I like the DARK layout!
Advertisement
IIRC DGRAM sockets don't listen at all (as they are not connection oriented). You just recv() off of them.
whoops :o, thanks very much.


I just have another question...


	if(!(he = gethostbyname("localhost")))		exit_err("error : no such host\n");	//...	their_addr.sin_addr = *((struct in_addr*)he->h_addr);

they generate compiler errors.

recv.c: In function `main':recv.c:28: warning: assignment makes pointer from integer without a castrecv.c:36: error: dereferencing pointer to incomplete type


I've tried

	if(!(he = (struct hostent*)gethostbyname("localhost")))		exit_err("error no such host\n");	their_addr.sin_addr = (struct in_addr)he->h_addr;

but im not sure if the in the first one I should be casting from int to hostent, and the second one it still complains about
recv.c: In function `main':recv.c:36: error: dereferencing pointer to incomplete type


Thanks

for the hostent error, I needed to include netdb.h


Accordining to the header netinet/in.h

     struct in_addr sin_addr;


so why does it err?



[Edited by - Genjix on January 15, 2005 11:49:18 AM]

This topic is closed to new replies.

Advertisement