Forum Discussion
Altera_Forum
Honored Contributor
15 years agoHere are the extracts of code which I think should contain all the information you need.
Basically the client (i.e. the remote end) sends out a UDP broadcast message containing the string "client broadcast". The client then sends back its IP address, ensuring it is byte swapped appropriately. The while (1) loop in this code is the very same while (1) loop found in the simple socket server example, where it is listening for the incoming connection on the fd_listen socket.
struct sockaddr_in bcast_addr;
/*
* Create a socket to listen for the UDP 'Hello' message from the client.
* We'll need to reply to this message with our IP address before the client
* can connect.
*/
if ((fd_bcast = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
alt_NetworkErrorHandler(EXPANDED_DIAGNOSIS_CODE," Bcast socket creation failed");
}
/*
* bind to the socket
*/
bcast_addr.sin_family = AF_INET;
bcast_addr.sin_port = htons(15000);
bcast_addr.sin_addr.s_addr = INADDR_ANY;
if ((bind(fd_bcast,(struct sockaddr *)&bcast_addr,sizeof(bcast_addr))) < 0)
{
alt_NetworkErrorHandler(EXPANDED_DIAGNOSIS_CODE," Bcast bind failed");
}
/*
* Now enter the main processing loop
*/
while(1)
{
FD_ZERO(&readfds);
FD_SET(fd_listen, &readfds);
FD_SET(fd_bcast, &readfds);
max_socket = fd_bcast+1;
if (conn.fd != -1)
{
FD_SET(conn.fd, &readfds);
if (max_socket <= conn.fd)
{
max_socket = conn.fd+1;
}
}
select(max_socket, &readfds, NULL, NULL, NULL);
if (FD_ISSET(fd_bcast, &readfds))
{
int bytes, addr_len=sizeof(addr);
char buffer;
bytes = recvfrom(fd_bcast, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, &addr_len);
ntohs(addr.sin_port), bytes);
if (strcmp(buffer, "client broadcast") == 0)
{
sendto(fd_bcast, buffer, bytes, 0, (struct sockaddr*)&addr, sizeof(addr));
}
}
...
}
I hope this helps! Matthew