Skip to content

Commit 7c80365

Browse files
committed
Fix broken SocketImpl for linux
1 parent 423c040 commit 7c80365

File tree

1 file changed

+39
-27
lines changed

1 file changed

+39
-27
lines changed

ArduinoCore-Linux/cores/arduino/SocketImpl.cpp

Lines changed: 39 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,43 @@ void SocketImpl::close() {
142142
::close(sock);
143143
}
144144

145-
#ifndef __APPLE__
146-
// The sysctl() method of getting the routing table information also
147-
// works in Linux, but is deprecated there.
145+
// Linux-compatible implementation: parse /proc/net/route for default interface
146+
#if defined(__linux__)
147+
static char *defaultInterface() {
148+
FILE *f;
149+
char line[256], *p, *c;
150+
151+
f = fopen("/proc/net/route", "r");
152+
if (!f) {
153+
return nullptr;
154+
}
155+
156+
// Skip the header line
157+
if (!fgets(line, sizeof(line), f)) {
158+
fclose(f);
159+
return nullptr;
160+
}
161+
162+
while (fgets(line, sizeof(line), f)) {
163+
p = strtok(line, " \t");
164+
c = strtok(NULL, " \t");
165+
166+
if (p != NULL && c != NULL) {
167+
if (strcmp(c, "00000000") == 0) {
168+
static char defaultInterface[IF_NAMESIZE];
169+
strncpy(defaultInterface, p, IF_NAMESIZE - 1);
170+
defaultInterface[IF_NAMESIZE - 1] = '\0';
171+
Logger.info("Default network interface is ", p);
172+
fclose(f);
173+
return defaultInterface;
174+
}
175+
}
176+
}
177+
fclose(f);
178+
return nullptr;
179+
}
180+
#elif defined(__APPLE__)
181+
// macOS/BSD implementation using sysctl
148182
static char *defaultInterface() {
149183
int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY};
150184
size_t needed = 0;
@@ -183,30 +217,8 @@ static char *defaultInterface() {
183217
return result;
184218
}
185219
#else
186-
char *defaultInterface() {
187-
FILE *f;
188-
char line[100], *p, *c;
189-
190-
f = fopen("/proc/net/route", "r");
191-
if (!f) {
192-
return nullptr;
193-
}
194-
195-
while (fgets(line, 100, f)) {
196-
p = strtok(line, " \t");
197-
c = strtok(NULL, " \t");
198-
199-
if (p != NULL && c != NULL) {
200-
if (strcmp(c, "00000000") == 0) {
201-
static char defaultInterface[20];
202-
strcpy(defaultInterface, p);
203-
Logger.info("Default network interface is ", p);
204-
fclose(f);
205-
return defaultInterface;
206-
}
207-
}
208-
}
209-
fclose(f);
220+
// Stub for other platforms
221+
static char *defaultInterface() {
210222
return nullptr;
211223
}
212224
#endif

0 commit comments

Comments
 (0)