@@ -123,7 +123,10 @@ void nmea_sentence_received(const char *sentence,
123
123
append_message (sentence );
124
124
125
125
if (sentences == 1 ) {
126
- if (send_nmea ( sentence , length ) == -1 ) abort ();
126
+ if (send_nmea ( sentence , length ) == -1 ){
127
+ fprintf (stderr ,"Error sending UDP packet with NMEA message: %s\n" , strerror (errno ));
128
+ abort ();
129
+ }
127
130
if (debug_nmea ) fprintf (stderr , "%s" , sentence );
128
131
} else {
129
132
if (buffer_count + length < MAX_BUFFER_LENGTH ) {
@@ -134,7 +137,10 @@ void nmea_sentence_received(const char *sentence,
134
137
}
135
138
136
139
if (sentences == sentencenum && buffer_count > 0 ) {
137
- if (send_nmea ( buffer , buffer_count ) == -1 ) abort ();
140
+ if (send_nmea ( buffer , buffer_count ) == -1 ){
141
+ fprintf (stderr ,"Error sending UDP packet with NMEA message (buffer_count=%d):%s\n" ,buffer_count , strerror (errno ));
142
+ abort ();
143
+ }
138
144
if (debug_nmea ) fprintf (stderr , "%s" , buffer );
139
145
buffer_count = 0 ;
140
146
};
@@ -203,16 +209,34 @@ int free_ais_decoder(void)
203
209
}
204
210
205
211
212
+
213
+ /* Check if the host is broacast address. I suppose there are better options than this :-| */
214
+ int isBroadcastAddress (const char * ipAddress ) {
215
+ // Find the last dot in the IP address
216
+ const char * lastDot = strrchr (ipAddress , '.' );
217
+ if (lastDot != NULL ) {
218
+ // Extract the last octet after the dot
219
+ const char * lastOctet = lastDot + 1 ;
220
+ // Check if the last octet is "255"
221
+ if (strcmp (lastOctet , "255" ) == 0 ) {
222
+ return 1 ; // Last digits are 255
223
+ }
224
+ }
225
+ return 0 ; //Last digits are not 255
226
+ }
227
+
228
+
229
+
206
230
int initSocket (const char * host , const char * portname ) {
207
231
struct addrinfo hints ;
232
+ int enable_broadcast = 1 ;
208
233
memset (& hints , 0 , sizeof (hints ));
209
234
hints .ai_family = AF_UNSPEC ;
210
235
hints .ai_socktype = SOCK_DGRAM ;
211
236
hints .ai_protocol = IPPROTO_UDP ;
212
237
#ifndef WIN32
213
238
hints .ai_flags = AI_ADDRCONFIG ;
214
239
#else
215
-
216
240
int iResult = WSAStartup (MAKEWORD (2 , 2 ), & wsaData );
217
241
if (iResult != 0 ) {
218
242
printf ("WSAStartup failed: %d\n" , iResult );
@@ -236,6 +260,14 @@ int initSocket(const char *host, const char *portname) {
236
260
#endif
237
261
return 0 ;
238
262
}
263
+ if (isBroadcastAddress (host )){
264
+ fprintf (stderr , "Broadcast address detected. Setting SO_BROADCAST option to socket.\n" );
265
+ // Enable sending broadcast packets
266
+ if (setsockopt (sock , SOL_SOCKET , SO_BROADCAST , & enable_broadcast , sizeof (enable_broadcast )) < 0 ) {
267
+ perror ("Failed to set socket option SO_BROADCAST:" );
268
+ exit (1 );
269
+ }
270
+ }
239
271
fprintf (stderr ,"AIS data will be sent to %s port %s\n" ,host ,portname );
240
272
return 1 ;
241
273
}
0 commit comments