use parseInt, avoid strndup

This commit is contained in:
john30
2015-11-07 14:22:04 +01:00
parent 8d81c39e52
commit a4fce959b5
+13 -12
View File
@@ -22,6 +22,7 @@
#endif #endif
#include "device.h" #include "device.h"
#include "data.h"
#include <unistd.h> #include <unistd.h>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
@@ -45,32 +46,32 @@ Device::~Device()
Device* Device::create(const char* name, const bool checkDevice, const bool readonly, Device* Device::create(const char* name, const bool checkDevice, const bool readonly,
void (*logRawFunc)(const unsigned char byte, bool received)) void (*logRawFunc)(const unsigned char byte, bool received))
{ {
if (strchr(name, '/') == NULL) { if (strchr(name, '/') == NULL && strchr(name, ':') != NULL) {
char* pos = strchr((char*)name, ':'); char* dup = strdup(name);
if (pos != NULL) { char* pos = strchr(dup, ':');
char* end = NULL; result_t result = RESULT_OK;
unsigned long int port = strtoul(pos+1, &end, 10); unsigned long int port = parseInt(pos+1, 10, 1, 65535, result);
if (end == NULL || end == pos+1 || *end != 0 || port < 1 || port > 65535) { if (result!=RESULT_OK) {
free(dup);
return NULL; // invalid port return NULL; // invalid port
} }
struct sockaddr_in address; struct sockaddr_in address;
memset((char*)&address, 0, sizeof(address)); memset((char*)&address, 0, sizeof(address));
char* host = strndup(name, pos-name); *pos = 0;
if (inet_aton(host, &address.sin_addr) == 0) { if (inet_aton(dup, &address.sin_addr) == 0) {
struct hostent* h = gethostbyname(host); struct hostent* h = gethostbyname(dup);
if (h == NULL) { if (h == NULL) {
free(host); free(dup);
return NULL; // invalid host return NULL; // invalid host
} }
memcpy(&address.sin_addr, h->h_addr_list[0], h->h_length); memcpy(&address.sin_addr, h->h_addr_list[0], h->h_length);
} }
free(host); free(dup);
address.sin_family = AF_INET; address.sin_family = AF_INET;
address.sin_port = htons((uint16_t)port); address.sin_port = htons((uint16_t)port);
return new NetworkDevice(name, address, readonly, logRawFunc); return new NetworkDevice(name, address, readonly, logRawFunc);
} }
}
return new SerialDevice(name, checkDevice, readonly, logRawFunc); return new SerialDevice(name, checkDevice, readonly, logRawFunc);
} }