Is there a way to make separate DNS requests for IPv4 and IPv6 in swift or ObjC - ios

What I have so far is:
void startQueryIPv4(const char *hostName){
printf("startQueryIPv4");
DNSServiceRef serviceRef;
DNSServiceGetAddrInfo(&serviceRef, kDNSServiceFlagsForceMulticast, 0, kDNSServiceProtocol_IPv4, hostName, queryIPv4Callback, NULL);
DNSServiceProcessResult(serviceRef);
DNSServiceRefDeallocate(serviceRef);
}
static void queryIPv4Callback(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *hostname, const struct sockaddr *address, uint32_t ttl, void *context){
printf("queryIPv4Callback");
if (errorCode == kDNSServiceErr_NoError) {
printf("no error");
char *theAddress = NULL;
switch(address->sa_family) {
case AF_INET: {
struct sockaddr_in *addr_in = (struct sockaddr_in *)address;
theAddress = malloc(INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(addr_in->sin_addr), theAddress, INET_ADDRSTRLEN);
break;
}
case AF_INET6: {
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)address;
theAddress = malloc(INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &(addr_in6->sin6_addr), theAddress, INET6_ADDRSTRLEN);
break;
}
default:
break;
}
printf("IP address: %s\n", theAddress);
free(theAddress);
} else {
printf("%d", errorCode);
}
}
But the callback is never called.
In the console I get this error: TIC Read Status [9:0x0]: 1:57
ObjectiveC is not my power but I had to mess with it. Any help will be appreciated.

Inasmuch as Objective-C is a true superset of C and Darwin is certified compatible with SUS 3, your Objective-C program for iOS should be able to use the C interface to the system's name resolver: getaddrinfo(). You can use the third argument to this function to specify that you want only IPv4 results (or only IPv6 results).
Things of which you should be aware:
this is of course a synchronous interface; if you want asynchronous then you'll need to arrange for that yourself.
getaddrinfo() allocates and returns a linked list of addresses, so
in principle, you might need to check more than one
you need to free the list after you're done with it via freeaddrinfo()

The reason you aren't getting a callback is that you aren't using a dispatch queue. The DNSServiceGetAddrInfo API is asynchronous. If you are doing this on an Apple device, you want something more like this:
void startQueryIPv4(const char *hostName) {
printf("startQueryIPv4");
DNSServiceRef serviceRef;
DNSServiceGetAddrInfo(&serviceRef, kDNSServiceFlagsForceMulticast, 0, kDNSServiceProtocol_IPv4, hostName, queryIPv4Callback, NULL);
main_queue = dispatch_get_main_queue();
DNSServiceSetDispatchQueue(sdref, main_queue);
dispatch_main();
}
Note that dispatch_main() is the main event loop for libdispatch: if you want to do other stuff, you need to schedule it in the dispatch loop, because dispatch_main() will not return.
In your original code you called DNSServiceRefDeallocate(), but you can't do that until you want to stop the query. If you call it right after you start the query, it will cancel the query. So e.g. you could call it from the callback.
However, a better flow would be to do a long-lived query (kDNSServiceFlagsLongLivedQuery) so that you get an update whenever the information changes. Of course you'd then need to change the host you're connecting to, so only do this if your application will be connected for an extended period.
Additionally, you may get more than one answer. If you do, it may be that some answers work to connect, and others don't. So you might like to accumulate answers and try each one, rather than giving up if the first answer you get doesn't work. The callback will include the kDNSServiceFlagsMoreComing flag if there is more data coming immediately. Each time the callback is called, it will get one answer (or an indication that the query has failed in some way).
Of course, this is a fairly low-level API. If you want to make your life a bit easier, you should use Network Framework. Network Framework does the "happy eyeballs" part for you—trying each response until it gets a connection, and returning you the connection it gets, canceling the others.
But you didn't ask about that, so I won't go into details here.

Related

lwIP mqtt connection error on stm32f4 discovery

I am trying to use lwIP for a client, which sends data to mosquitto broker on stm32f407 discovery.
Mqtt application is implemented at lwIP. I just use them like that at main after initializing.
mqtt_client_t static_client;
Afterwards, with USART interrupt, I call
example_do_connect(&static_client); example_publish(&static_client,0);
Which calls those functions:
{
struct mqtt_connect_client_info_t ci;
err_t err;
/* Setup an empty client info structure */
memset(&ci, 0, sizeof(ci));
/* Minimal amount of information required is client identifier, so set it here */
ci.client_id = "lwip_test";
ci.client_user = NULL;
ci.client_pass = NULL;
/* Initiate client and connect to server, if this fails immediately an error code is returned
otherwise mqtt_connection_cb will be called with connection result after attempting
to establish a connection with the server.
For now MQTT version 3.1.1 is always used */
err = mqtt_client_connect(client, &serverIp, MQTT_PORT, mqtt_connection_cb, 0, &ci);
/* For now just print the result code if something goes wrong*/
if(err != ERR_OK) {
}
}
and
void example_publish(mqtt_client_t *client, void *arg)
{
const char *pub_payload= "stm32_test";
err_t err;
u8_t qos = 2; /* 0 1 or 2, see MQTT specification */
u8_t retain = 0; /* No don't retain such crappy payload... */
err = mqtt_publish(client, "pub_topic", pub_payload, strlen(pub_payload), qos, retain, mqtt_pub_request_cb, arg);
if(err != ERR_OK) {
// printf("Publish err: %d\n", err);
err = ERR_OK;
}
}
/* Called when publish is complete either with sucess or failure */
static void mqtt_pub_request_cb(void *arg, err_t result)
{
if(result != ERR_OK) {
// printf("Publish result: %d\n", result);
}
}
I am able to ping board, my IP adress has been assigned in main by using IP_ADDR4(&serverIp, 192,168,2,97);
I've used all needed functions like MX_LWIP_Init(), MX_LWIP_Process() and actually i am even able to implement a TCP client, which is working nice. So internet connection is well, but I guess, there is a point that i missed in mqttclient. Callbacks is also have done by Erik Anderssen's guide.
When i try to subscribe to board's IP by using mosquitto, Error: no connection could be made because the target actively refused it. If you notice some point that i have missed or have an idea, please let me know.
Any help will appreciated, thanks in advance.
I had a similar problem that the server refused the connection when QoS (quality of service) was set to 2, but the server needed it to be 0. Try changing the parameter qos in the line in the connection callback to either 0 or 1:
err = mqtt_subscribe(mqtt.client, "topic", qos, MqttApp_SubscribeRequestCallback, arg);
Same applies to the parameter qos in the publish function:
change u8_t qos = 2; to u8_t qos = 0; (or 1 - whatever your server requires)
Hope it helps. Cheers.

How to find last relay node of a data packet in-transit?

I'm trying to implement a security mechanism in RPL. For this, I need to log where did a packet come from. For example, if a packet is transmitted from A-->B-->C-->D, I want to find out at C that the packet came through B, and similarly for D.
I've added some code in uip6.c file to pull up the sender address from packetbuffer, but it is always null.
I'm storing the last node address and the time when the complete packet was received. These are the data structures.
struct packet_time_entry {
linkaddr_t *source;
uint32_t time;
};
MEMB(packet_time_mem, struct packet_time_entry, 16);
LIST(packet_time);
The main code I've written so far is this, in uip_process(), below line 1108 (master branch).
struct packet_time_entry *p = memb_alloc(&packet_time_mem);
p->time = clock_time();
linkaddr_copy(p->source, packetbuf_addr(PACKETBUF_ADDR_SENDER));
struct packet_time_entry *i;
for (i = list_head(packet_time); i != NULL; i = list_item_next(i)) {
if (linkaddr_cmp(i->source, p->source))
list_remove(packet_time, i);
}
list_add(packet_time, p);
PRINTF("Entry ");
PRINTLLADDR((uip_lladdr_t*) p->source); // always NULL
PRINTF("| %lu", p->time);
PRINTF("\n");
I expect it to give me the address from packetbuf, but it's always NULL. Also, I suspect it is run only at the destination node, but not at the intermediate nodes.
You can DEBUG the execution. For that just set DEBUG_NONE TO DEBUG_PRINT in uip6.c and then parse the serial log for finding the path taken by the packet.

Http client mode with Contiki?

I want to make a webAPI call from a sensor using http, is it possible to do http requests using Contiki OS?
As far as I've searched I found only coap client examples.
Check the examples/http-socket example, it shows how to use CRUD methods such as PUT, GET, etc.
Here's the link to the example (working with the latest master commit)
This example relies on IP64, but can be changed to work with IPv6, basically you need to include the http-socket library. Here are the more relevant parts of the example:
#include "contiki-net.h"
#include "http-socket.h"
#include "ip64-addr.h"
#include <stdio.h>
static struct http_socket s;
static int bytes_received = 0;
static void
callback(struct http_socket *s, void *ptr,
http_socket_event_t e,
const uint8_t *data, uint16_t datalen)
{
if(e == HTTP_SOCKET_ERR) {
printf("HTTP socket error\n");
} else if(e == HTTP_SOCKET_DATA) {
bytes_received += datalen;
printf("HTTP socket received %d bytes of data\n", datalen);
}
}
PROCESS_THREAD(http_example_process, ev, data)
{
PROCESS_BEGIN();
/* Initializes the socket */
http_socket_init(&s);
/* GET request */
http_socket_get(&s, "http://www.contiki-os.org/", 0, 0,
callback, NULL);
/* Waits forever for the HTTP callback */
while(1) {
PROCESS_WAIT_EVENT_UNTIL(0);
}
PROCESS_END();
}
Yes you can do that:
What I understand is that you are looking for Websense Example in Contiki OS.it uses HTTP protocl.
A: so find this file.
~/contiki/examples/zolertia/z1/ipv6/z1-websense/z1-websense.c
Burn it on Sender Mote.
Burn border-router.c file located in /home/superuser/contiki/examples/ipv6/rpl-border-router/
Connect Border Router with tunnelslip with command make connect-router.
use the HTTP IPV6 url shown by tunnelslip on connection.
this url in browser will give you address of motes connected to it.
use that sender mote address in web browser and see the mote output.
B: or from contiki/cooja simulator:
launch this project file. this is working demo for the websense.
~contiki/examples/zolertia/z1/ipv6/z1-websense/example-z1-websense.csc
and repeat from step 3.
for further you can ask me.

Arduino WiFi shield post with header problems

I'm trying to do a post from the arduino wifi shield to my java servlet. The servlet functions with url get, and jquery post, but I can't sort the headers out in my arduino code. Any help will be greatly appreciated!
The server returns 200, but I'm not getting the payload "content" as value. I'm not exactly sure what I'm doing wrong but I'm pretty sure it's in how my headers are setup. I've spent the last two days trying to get it.
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "jesussavesforjust19.95"; // your network SSID (name)
char pass[] = "********"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
IPAddress server(192,168,10,149); // numeric IP for Google (no DNS)
WiFiClient client;
void setup() {
Serial.begin(9600);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.println("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
sendData("0600890876");
}
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.println(c);
}
//String dataString = "060088765";
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
//sendData(dataString);
for(;;)
;
}
}
// this method makes a HTTP connection to the server:
void sendData(String thisData) {
// if there's a successful connection:
Serial.println("send data");
if (client.connect(server, 8080)) {
String content = "value=0600887654";
Serial.println(content);
Serial.println("connected");
client.println("POST /hos HTTP/1.1");
client.println("Host:localhost");
client.println("Connection:Keep-Alive");
client.println("Cache-Control:max-age=0");
client.println("Content-Type: application/x-www-form-urlencoded\n");
client.println("Content-Length: ");
client.println(content.length());
client.println("\n\n");
client.println(content);
}
else {
// if you couldn't make a connection:
Serial.println("form connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.println("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.println("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.println("signal strength (RSSI):");
Serial.println(rssi);
Serial.println(" dBm");
}
Perhaps, some of your "Serial.println" and "client.println" commands should be "Serial.print" and "client.print" instead. For example:
client.print("Content-Length: ");
client.println(content.length());
would avoid adding a line break between the text and the number.
This is maybe more advice on an approach than an answer.
If I was doing something like this I would not start on the Arduino. The endless compile, download, run, look at print()'s would drive me crazy. I would fully prototype the client/server interaction in whatever you have at your fingertips, preferably something with a debugger. (Java, Python, PHP, VB, whatever you know that you can slap together)
Second, I would run Wireshark on the server so that I could see exactly what was being sent and responded.
Then I would port the same interaction over to the Arduino. Again inspect with Wireshark to confirm you are getting what you expected. If you send the same bytes, you should get the same response.
Even if you choose to implement straight on Arduino, consider having Wireshark to capture the actual network traffic.
With Wireshark, you might see that the Arduino println() is not sending the correct line end for the server.
Also, there is no guarantee that last println() is actually sent. The network stack implementation is free to buffer as it sees fit. You might need a flush(). A packet trace would show this.
With a packet capture you might find that time matters. In theory TCP is a stream and you should be able to send that POST data 1 character at a time in 1 packet and everything would work. But the Arduino might be so slow executing those println()'s by the server's standards that it times out. In such case you would see the server respond before the Arduino even finished sending.

bytesWritten, but other device never receives NSStreamEventHasBytesAvailable event

I have set up a Bonjour network between an iPhone and a Mac.
The user chooses the iPhone’s net service in a table presented in the Mac, and a pair of streams are created and opened on both sides.
The iPhone starts by sending a code (an integer) to the Mac. The Mac successfully receives it.
After a pause for user input and processing, the Mac initiates sending a code to the iPhone:
NSInteger bytesWritten = [self.streamOut write:buffer maxLength:sizeof(uint8_t)];
// bytesWritten is 1.
But the iPhone never gets an NSStreamEventHasBytesAvailable event. I double-checked just before this point, and streamStatus on the iPhone’s NSInputStream is 2, which is NSStreamStatusOpen, as it should be.
Any ideas what could be wrong?
Update: I ran a test in which the Mac was the first to send an integer to the iPhone. Again, I got a bytesWritten of 1 from the Mac’s output stream, but the iPhone never got a NSStreamEventHasBytesAvailable event.
So there must be something wrong with the iPhone’s input stream. But I doublechecked:
iPhone’s self.streamIn is correctly typed as NSInputStream in the h file
iPhone receives 2 NSStreamEventOpenCompleted events, and I check the class of the stream arg. One isKindOfClass:[NSOutputStream class], the other isn’t.
iPhone never receives NSStreamEventEndEncountered, NSStreamEventErrorOccurred, or NSStreamEventNone.
As noted above, following the Mac’s write to output stream, iPhone’s input stream status is 2, NSStreamStatusOpen.
Here is the code used to create the iPhone's input stream. It uses CF types because it's done in the C-style socket callback function:
CFReadStreamRef readStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);
if (readStream) {
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
server.streamIn = (NSInputStream *)readStream;
server.streamIn.delegate = server;
[server.streamIn scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
if ([server.streamIn streamStatus] == NSStreamStatusNotOpen)
[server.streamIn open];
CFRelease(readStream);
}
Update2: Info responsive to alastair’s comment:
Socket Options
The retain, release, and copyDescription callbacks are set to NULL. The optionFlags are set to acceptCallback.
Socket Creation
Here’s the method used to set up the socket on both the iPhone and the Mac, complete with my commented attempts to figure out what is actually going on in this code, which was adapted from various tutorials and experiments (which worked):
/**
Socket creation, port assignment, socket scheduled in run loop.
The socket represents the port on this app's end of the connection.
*/
- (BOOL) makeSocket {
// Make a socket context, with which to configure the socket.
// It's a struct, but doesn't require "struct" prefix -- because typedef'd?
CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL}; // 2nd arg is pointer for callback function
// Make socket.
// Sock stream goes with TCP protocol, the safe method used for most data transmissions.
// kCFSocketAcceptCallBack accepts connections automatically and presents them to the callback function supplied in this class ("acceptSocketCallback").
// CFSocketCallBack, the callback function itself.
// And note that the socket context is passed in at the end.
self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&acceptSocketCallback, &socketCtxt);
// Do socket-creation error checking.
if (self.socket == NULL) {
// alert omitted
return NO;
}
// Prepare an int to pass to setsockopt function, telling it whether to use the option specified in arg 3.
int iSocketOption = 1; // 1 means, yes, use the option
// Set socket options.
// arg 1 is an int. C-style method returns native socket.
// arg 2, int for "level." SOL_SOCKET is standard.
// arg 3, int for "option name," which is "uninterpreted." SO_REUSEADDR enables local address reuse. This allows a new connection even when a port is in wait state.
// arg 4, void (wildcard type) pointer to iSocketOption, which has been set to 1, meaning, yes, use the SO_REUSEADDR option specified in arg 3.
// args 5, the size of iSocketOption, which can now be recycled as a buffer to report "the size of the value returned," whatever that is.
setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, (void *)&iSocketOption, sizeof(iSocketOption));
// Set up a struct to take the port assignment.
// The identifier "addr4" is an allusion to IP version 4, the older protocol with fewer addresses, which is fine for a LAN.
struct sockaddr_in addr4;
memset(&addr4, 0, sizeof(addr4));
addr4.sin_len = sizeof(addr4);
addr4.sin_family = AF_INET;
addr4.sin_port = 0; // this is where the socket will assign the port number
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
// Convert to NSData so struct can be sent to CFSocketSetAddress.
NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)];
// Set the port number.
// Struct still needs more processing. CFDataRef is a pointer to CFData, which is toll-free-bridged to NSData.
if (CFSocketSetAddress(socket, (CFDataRef)address4) != kCFSocketSuccess) {
// If unsuccessful, advise user of error (omitted)…
// ... and discard the useless socket.
if (self.socket)
CFRelease(socket);
self.socket = NULL;
return NO;
}
// The socket now has the port address. Extract it.
NSData *addr = [(NSData *)CFSocketCopyAddress(socket) autorelease];
// Assign the extracted port address to the original struct.
memcpy(&addr4, [addr bytes], [addr length]);
// Use "network to host short" to convert port number to host computer's endian order, in case network's is reversed.
self.port = ntohs(addr4.sin_port);
printf("\nUpon makeSocket, the port is %d.", self.port);// !!!:testing - always prints a 5-digit number
// Get reference to main run loop.
CFRunLoopRef cfrl = CFRunLoopGetCurrent();
// Schedule socket with run loop, by roundabout means.
CFRunLoopSourceRef source4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
CFRunLoopAddSource(cfrl, source4, kCFRunLoopCommonModes);
CFRelease(source4);
// Socket made
return YES;
}
Runloop Scheduling
Yes, all 4 streams are scheduled in the runloop, all using code equivalent to what I posted in the first update above.
Runloop Blocking:
I’m not doing anything fancy with synchronization, multiple threads, NSLocks, or the like. And if I set a button action to print something to the console, it works throughout — the runloop seems to be running normally.
Update4, Stream Ports?
Noa's debugging suggestion gave me the idea to examine the stream properties further:
NSNumber *nTest = [self.streamIn propertyForKey:NSStreamSOCKSProxyPortKey]; // always null!
I had assumed that the streams were hanging onto their ports, but surprisingly, nTest is always null. It's null in my apps, which would seem to point to a problem -- but it's also null in a tutorial app that works. If a stream doesn't need to hang onto its port assignment once created, what is the purpose of the port property?
Maybe the port property is not accessible directly? But nTest is always null in the following, too:
NSDictionary *dTest = [theInStream propertyForKey:NSStreamSOCKSProxyConfigurationKey];
NSNumber *nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
NSLog(#"\tInstream port is %#.", nTest); // (null)
nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
NSLog(#"\tOutstream port is %#.", nTest); // (null)
The trouble was this line:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);
This would have been OK if I were only receiving data on the iPhone end. But I was creating a pair of streams, not just an input stream, so below this code I was creating a write stream:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, NULL, &writeStream);
The CFStream Reference says, “If you pass NULL [for readStream], this function will not create a readable stream.” It doesn’t say that if you pass NULL, you’ll render a previously created stream inoperable. But that is apparently what happens.
One strange artifact of this setup was that if I opened the streamIn first, I would have the opposite problem: The iPhone would get hasByteAvailable events, but never a hasSpaceAvailable event. And as noted in the question, if I queried the streams for their status, both would return NSStreamStatusOpen. So it took a long time to figure out where the real mistake was.
(This sequential stream creation was an artifact of a test project I had set up months before, in which I tested data moving in only one direction or the other.)
SOLUTION
Both streams should be created as a pair, in one line:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, &writeStream);

Resources