I have a question:
Is there any way and if there is how I can discover server address via broadcasts from client's point of view?
I read almost everything on the Internet and there is no information how I can discover server address without knowing its name (gethostbyname()). I need to create a client-server application with UDP where a Server sends broadcast and clients are supposed to discover it and send some text back to it.
As far as I know the client needs to create a socket then get host (server) address by gethostbyname() in order to have an address on which it could recvfrom() and then perform i.e. sendto().
Basically server starts only with port (command line parameter) on which creates its socket and bind() and client is also started with only port (command line parameter) and is supposed to discover server address via broadcasts. This is what I have so far:
SERVER:
struct sockaddr_in addr;
int socketfd,t=1;
socketfd = make_socket(PF_INET,type);
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR,&t, sizeof(t))) ERR("setsockopt");
if(bind(socketfd,(struct sockaddr*) &addr,sizeof(addr)) < 0) ERR("bind");
Then I would like to broadcast it to everywhere in the subnetwork from server but dunno why:(
CLIENT:
struct sockaddr_in addr;
struct hostent *hostinfo;
addr.sin_family = AF_INET;
addr.sin_port = htons (port);
hostinfo = gethostbyname(address);
if(hostinfo == NULL)HERR("gethostbyname");
addr.sin_addr = *(struct in_addr*) hostinfo->h_addr;
Here I would like to receive in some way what server broadcasted and send back some text.
EDIT: I would do that by:
int fd;
struct sockaddr_in addr;
fd = socket(PF_INET, SOCK_DGRAM, 0);
char buf[TEXT_SIZE];
socklen_t size=sizeof(addr);
recvfrom(fd, (char *)buf, sizeof(char[FILE_SIZE]), 0, &addr, &size);
But how do I set server to broadcast it so that client from the above code could receive it? I always sent it by:
sendto(fd, (char *)some_buffer, sizeof(some_buffer), 0, &addr, sizeof(addr));
But my server cannot discover clients addr
because it has to first send the broadcast to all clients. So I cannot fill addr
here because it is not set yet. Is there any way that server would first broadcast the message without knowing clients address? Server only creates a socket binds it and then needs to immediately broadcast some text. Thank you for replies.