Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- + (void) doBrowseForServers
- {
- // http://mbielanczuk.com/2013/07/browsing-network-for-sql-server-instances-in-c/
- // used as a reference.
- SOCKET sock;
- int broadcast = 1;
- struct timeval timeout;
- timeout.tv_sec = 5; // 10 second timeout
- timeout.tv_usec = 0;
- if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
- {
- NSLog(@"MSSQLBrowserServiceClient failed to initialize socket.");
- return;
- }
- // Setting socket broadcast option.
- if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast)) == -1)
- {
- NSLog(@"MSSQLBrowserServiceClient failed to set broadcast option.");
- return;
- }
- // Set a timeout so that we do not wait forever.
- if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) == -1)
- {
- NSLog(@"MSSQLBrowserServiceClient failed to set send timeout.", errno);
- return;
- }
- // Set a timeout so that we do not wait forever.
- if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) == -1)
- {
- NSLog(@"MSSQLBrowserServiceClient failed to set receive timeout.", errno);
- return;
- }
- if(sendBroadcast(sock, MSSQL_BROWSER_SERVICE_PORT))
- {
- NSString * response = [self reciveBroadcastRespondFromSocket: sock
- usingPort: MSSQL_BROWSER_SERVICE_PORT];
- NSDate * lastSeen = [NSDate date];
- if(0 != response.length)
- {
- // Processing code omitted to focus on send/receive
- } // End of we had responses
- }
- else
- {
- NSLog(@"MSSQLBrowserServiceClient failed to browse for servers.");
- }
- } // End of beginBrowseForServers
- bool sendBroadcast(SOCKET sock, int port)
- {
- struct sockaddr_in bcastAddr;
- memset(&bcastAddr, 0, sizeof(bcastAddr));
- bcastAddr.sin_family = AF_INET;
- bcastAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
- bcastAddr.sin_port = htons(port);
- char query = 0x02;
- if (sendto(sock, &query, sizeof(query), 0, (struct sockaddr *)&bcastAddr, sizeof(bcastAddr)) == -1)
- {
- return 0;
- }
- return 1;
- }
- + (NSString*) reciveBroadcastRespondFromSocket: (SOCKET) sock
- usingPort: (int) port
- {
- ssize_t recvBytes = 0;
- char buf[512] = {0x00};
- memset(buf,'