Skip to content

Instantly share code, notes, and snippets.

@smulewicz smulewicz/ssdp.cpp
Last active Aug 11, 2019

Embed
What would you like to do?
Windows / C++ / Wyszukanie adresu IP urządzenia UPnP.
#include <string>
#include <vector>
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std;
inline vector<string> splitString(const string &s, const string &delimiter {
vector<string> ret;
size_t start = 0;
size_t end = 0;
size_t len = 0;
string token;
do {
end = s.find(delimiter,start);
len = end - start;
token = s.substr(start, len);
ret.emplace_back(token);
start += len + delimiter.length();
}
while(end != string::npos);
return ret;
}
int inet_pton(int af, const char *src, void *dst) {
struct sockaddr_storage ss;
int size = sizeof(ss);
char src_copy[INET6_ADDRSTRLEN + 1];
ZeroMemory(&ss, sizeof(ss));
strncpy(src_copy, src, INET6_ADDRSTRLEN + 1);
src_copy[INET6_ADDRSTRLEN] = 0;
if(WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0) {
switch(af) {
case AF_INET:
*(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
return 1;
case AF_INET6:
*(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
return 1;
}
}
return 0;
}
int main() {
// TUTAJ podajemy identyfikator urządzenia UPnP.
const char* pkt = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nST: TUTAJ\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\n\r\n";
const char* srcIP = "";
const char* destIP = "239.255.255.250";
sockaddr_in dest;
sockaddr_in local;
WSAData data;
WSAStartup(MAKEWORD(2, 2), &data);
ULONG* srcAddr = new ULONG;
ULONG* destAddr = new ULONG;
local.sin_family = AF_INET;
inet_pton(AF_INET, srcIP, srcAddr);
local.sin_addr.s_addr = *srcAddr;
local.sin_port = htons(0);
dest.sin_family = AF_INET;
inet_pton(AF_INET, destIP, destAddr);
dest.sin_addr.s_addr = *destAddr;
dest.sin_port = htons(1900);
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct hostent *pHost = 0;
pHost = ::gethostbyname("");
char aszIPAddresses[10][16];
for(int nCount = 0; ((pHost->h_addr_list[nCount]) && (nCount < 10)); ++nCount) {
memcpy(&local.sin_addr, pHost->h_addr_list[nCount], pHost->h_length);
}
bind(s, (sockaddr *)&local, sizeof(local));
sendto(s, pkt, strlen(pkt), 0, (sockaddr*)&dest, sizeof(dest));
char buff[1024];
int len = 0;
socklen_t sendsize = sizeof(local);
DWORD timeout = 1000;
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
len = recvfrom(s, buff, 1024, 0, (sockaddr*)&local, &sendsize);
if(len > 0) {
vector<string> v1 = splitString(buff, "\r\n");
for(auto i = 0; i < v1.size(); ++i) {
vector<string> v2 = splitString(v1[i], ": ");
if(v2[0] == "LOCATION") {
vector<string> v3 = splitString(v2[1], "/");
vector<string> v4 = splitString(v3[2], ":");
cout << v4[0];
}
}
}
delete srcAddr;
delete destAddr;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.