MCPcopy Create free account
hub / github.com/LemonOSProject/LemonOS / main

Function main

System/NetworkGovernor/main.cpp:32–94  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

30}
31
32int main(){
33 dhcpSocket = socket(AF_INET, SOCK_DGRAM, 0);
34
35 if(!dhcpSocket){
36 perror("[NetworkGovernor] Could not open UDP socket: ");
37 return -1;
38 }
39
40 dhcpClientAddress.sin_family = AF_INET;
41 dhcpClientAddress.sin_addr.s_addr = 0;
42 dhcpClientAddress.sin_port = htons(68);
43
44 if(bind(dhcpSocket, (sockaddr*)&dhcpClientAddress, sizeof(sockaddr_in))){
45 perror("[NetworkGovernor] Could not bind UDP to port 67: ");
46 return -2;
47 }
48
49 dhcpServerAddress.sin_addr.s_addr = inet_addr("255.255.255.255"); // Broadcast
50 dhcpServerAddress.sin_family = AF_INET;
51 dhcpServerAddress.sin_port = htons(67);
52
53 timespec t;
54 clock_gettime(CLOCK_BOOTTIME, &t);
55
56 DHCPHeader header;
57 header.op = DHCPOpCodeDiscover;
58 header.htype = DHCPHardwareTypeEthernet;
59 header.hlen = 6; // MAC addresses are 6 bytes long
60 header.hops = 0;
61 header.xID = rand() * (t.tv_sec + t.tv_nsec); // Generate random id
62 header.secs = 0;
63 header.flags = DHCP_FLAG_BROADCAST;
64 header.clientIP = 0; // Don't worry about endianess 0.0.0.0 is symmetrical
65 header.yourIP = 0;
66 header.serverIP = 0;
67 header.gatewayIP = 0;
68 memcpy(header.clientAddress, "\xde\xad\x69\xbe\xef\x42", 6); // TODO: ioctl() for getting MAC address
69 header.cookie = DHCP_MAGIC_COOKIE;
70
71 std::vector<void*> options;
72
73 DHCPOption<1> dhcpMessage;
74 dhcpMessage.length = 1;
75 dhcpMessage.optionCode = DHCPOptionMessageType;
76 dhcpMessage.data[0] = DHCPMessageTypeDiscover;
77
78 DHCPOption<3> dhcpParameters;
79 dhcpParameters.length = 3;
80 dhcpParameters.optionCode = DHCPOptionParameterRequestList;
81 dhcpParameters.data[0] = DHCPOptionSubnetMask;
82 dhcpParameters.data[1] = DHCPOptionDefaultGateway;
83 dhcpParameters.data[2] = DHCPOptionDNS;
84
85 options.push_back((void*)&dhcpMessage);
86 options.push_back((void*)&dhcpParameters);
87
88 SendDHCPMessage(header, options);
89

Callers

nothing calls this directly

Calls 3

randFunction · 0.85
memcpyFunction · 0.85
SendDHCPMessageFunction · 0.85

Tested by

no test coverage detected