exception error in pcap.net - runtime-error

i am using pcap.net to change packets and reconstruct an output pcap file. but in this part i have error.
could anyone say, how could i solve it?
if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
{
PayloadLayer Payload = null;
if ((packet.Ethernet.IpV4.Tcp.Payload != null) && (packet.Ethernet.IpV4.Tcp.Payload.Length >= 0))
{
Payload = (PayloadLayer)packet.Ethernet.IpV4.Tcp.Payload.ExtractLayer(); //extract the data
tmpPacket = PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, tcpLayer, Payload);
}
else
{
tmpPacket = PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, tcpLayer);
}
}
this is my error :
Object reference not set to an instance of an object .(for ipv4Layer)
and the detail of the error:
Length = 'ipV4Layer.Length' threw an exception of type 'System.NullReferenceException'

Related

InputStream never calls hasBytesAvailable

I'm trying to get iOS devices to discover each other with Bonjour and then connect with InputStream and OutputStream.
The devices can connect to each other, but sending bytes from one device's OutputStream will not trigger the "hasBytesAvailable" event on the other device.
Because I want devices to connect with multiple other devices, I've wrapped each connection in an "ASPeer" object, which I can put in an array to keep track of all my connections.
class ASPeer: NSObject {
let service: NetService
var inputStream: InputStream?
var outputStream: OutputStream?
init(_ service: NetService) {
self.service = service
}
func openStreams() {
guard let inputStream = inputStream, let outputStream = outputStream else {
fatalError("openStreams: failed to get streams!")
}
inputStream.delegate = self
inputStream.schedule(in: .current, forMode: .defaultRunLoopMode)
inputStream.open()
outputStream.delegate = self
outputStream.schedule(in: .current, forMode: .defaultRunLoopMode)
outputStream.open()
}
func closeStreams() {
guard let inputStream = inputStream, let outputStream = outputStream else {
fatalError("closeStreams: failed to get streams!")
}
inputStream.remove(from: .current, forMode: .defaultRunLoopMode)
inputStream.close()
inputStream.delegate = nil
outputStream.remove(from: .current, forMode: .defaultRunLoopMode)
outputStream.close()
outputStream.delegate = nil
}
}
extension ASPeer: StreamDelegate {
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch aStream {
case inputStream!:
switch eventCode {
case .openCompleted:
print("inputOpenCompleted:")
case .hasBytesAvailable:
print("inputHasBytesAvailable:")
var readData = [UInt8](Data(capacity: 4096))
let bytesRead = inputStream!.read(&readData, maxLength: 4096)
if bytesRead > 0 {
print(String(bytes: readData, encoding: .ascii)!)
}
case .errorOccurred:
print("inputErrorOccurred")
case .endEncountered:
print("inputEndEncountered")
default:
break
}
case outputStream!:
switch eventCode {
case .openCompleted:
print("outputOpenCompleted:")
case .hasSpaceAvailable:
print("outputHasSpaceAvailable:")
case .errorOccurred:
print("outputErrorOccurred")
case .endEncountered:
print("outputEndEncountered")
default:
break
}
default:
print("got unknown stream!")
}
}
}
I've added print statements to every single "handle" event for my input and output streams. Here are the output logs when I run the app and try to get the devices to talk to each other:
Device 1
inputOpenCompleted:
outputOpenCompleted:
outputHasSpaceAvailable:
Device 2
inputOpenCompleted:
outputOpenCompleted:
outputHasSpaceAvailable:
When I try to send a message from Device 1 to Device 2, I'm expecting Device 2 to print out "inputHasBytesAvailable". However, I just get extra lines of "outputHasSpaceAvailable" from Device 1:
Device 1
inputOpenCompleted:
outputOpenCompleted:
outputHasSpaceAvailable:
outputHasSpaceAvailable: <--
outputHasSpaceAvailable: <--
Device 2
inputOpenCompleted:
outputOpenCompleted:
outputHasSpaceAvailable:
<-- I'm expecting "inputHasBytesAvailable" here!
What could the issue be? I've double checked my run loops and made sure they are correct. Also, there seems to be a bug with "getInputStream" and I made sure to call "getInputStream" on the main queue to avoid that problem. Is there something else I'm missing?
In addition, I also have a BonjourManager object that manages every one of these "ASPeer" connections. The BonjourManager is what actually creates the connections and sends writes to the OutputStreams.
class ASBonjourManager: NetServiceDelegate {
var peers = [ASPeer]()
// ... more code here but omitted
func netService(_ sender: NetService, didAcceptConnectionWith inputStream: InputStream, outputStream: OutputStream) {
if sender == advertiser {
return
}
if let peer = peers.first(where: { $0.service == sender }) {
OperationQueue.main.addOperation {
// Due to a bug <rdar://problem/15626440>, this method is called on some unspecified
// queue rather than the queue associated with the net service (which in this case
// is the main queue). Work around this by bouncing to the main queue.
assert((peer.inputStream == nil) == (peer.outputStream == nil))
if let _ = peer.inputStream, let _ = peer.outputStream {
inputStream.open()
inputStream.close()
outputStream.open()
outputStream.close()
} else {
peer.inputStream = inputStream
peer.outputStream = outputStream
peer.openStreams()
}
}
} else {
OperationQueue.main.addOperation {
let newPeer = ASPeer(sender)
sender.delegate = self
newPeer.inputStream = inputStream
newPeer.outputStream = outputStream
newPeer.openStreams()
self.peers.append(newPeer)
}
}
}
func connectTo(service: NetService) {
var inStream: InputStream?
var outStream: OutputStream?
let peer = peers.first(where: { $0.service.isEqual(service) })!
//assert(peer.inputStream == nil && peer.outputStream == nil)
if peer.inputStream != nil && peer.outputStream != nil {
return
}
if service.getInputStream(&inStream, outputStream: &outStream) {
peer.inputStream = inStream
peer.outputStream = outStream
peer.openStreams()
} else {
print("getInputStream failed!")
}
}
func sendMessage(_ service: NetService) {
let peer = peers.first(where: { $0.service.isEqual(service) })!
if peer.outputStream!.hasSpaceAvailable {
let message = Array("hello world".utf8)
peer.outputStream!.write(message, maxLength: message.count)
}
}
}

how to handle stale event in nginx

These days, I am studying the nginx source code.
But there is a question about stale event.
If there is some coming event : #1, #2,#3 .. #40,
When we deal with #1, #40 will shut down and it's variables instance is 0
and #2.#3 is a new connection,
Accept function to allocate a new descriptor which is just free (#40),
when we deal with #2,
we need to invoke function named ngx_event_accept, and then invoke ngx_get_connection,
but unfortunately after that ,we failed which mean we need to free connection,but we have invoked ngx_get_connection once which means variables instance have changed once.
just like the following code (success and failed )
void ngx_event_accept(ngx_event_t *ev)
{
...
/* success */
c = ngx_get_connection(s, ev->log);
if (c == NULL) {
if (ngx_close_socket(s) == -1) {
ngx_log_error(NGX_LOG_ALERT, ev->log, ngx_socket_errno,
ngx_close_socket_n " failed");
}
return;
}
c->type = SOCK_STREAM;
...
/* failed */
c->pool = ngx_create_pool(ls->pool_size, ev->log);
if (c->pool == NULL) {
ngx_close_accepted_connection(c);
return;
}
c->sockaddr = ngx_palloc(c->pool, socklen);
if (c->sockaddr == NULL) {
ngx_close_accepted_connection(c);
return;
}
ngx_memcpy(c->sockaddr, sa, socklen);
/* or failed here */
log = ngx_palloc(c->pool, sizeof(ngx_log_t));
if (log == NULL) {
ngx_close_accepted_connection(c);
return;
}
....
}
when we deal with #3,we success, the fd set to 40, and the value of instance is changed again.
Now it's the same with before, so the following Judgment statement in the function named ngx_epoll_process_events will not work,
if (c->fd == -1 || rev->instance != instance) {
/*
* the stale event from a file descriptor
* that was just closed in this iteration
*/
ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
"epoll: stale event %p", c);
continue;
}
I know it can post event which put in in queue not handle,but if i don't use ngx_use_accept_mutex,which means the flag in function ngx_process_events_and_timers doesn't include NGX_POST_EVENTS,
in this case,it will not post event but handle event immediately and it's wrong because #40 is stale event.

I want my multihopOscilloscope to send data through radio and Serial port as well

I am trying to modify the multihop Oscilloscope program so that the sink node is able to send data both to UART and radio medium as well. As far as researched, I found out that the same hardware is used for sending packets via UART and radio too.
In this case, how do I modify my code so that I can send data to UART or radio based on a condition I receive. Here in the sample prorgram, I send data via radio on every 10 packets received.
The receive module for my sink node is:
event message_t* Receive.receive(message_t* msg, void *payload, uint8_t len) {
oscilloscope_t* in = (oscilloscope_t*)payload;
counter++;
am_addr_t rec = call AMPacket.source(msg);
oscilloscope_t* out;
counter++;
call Leds.led0On();
if (uartbusy == FALSE) {
out = (oscilloscope_t*)call SerialSend.getPayload(&uartbuf, sizeof(oscilloscope_t));
if (len != sizeof(oscilloscope_t) || out == NULL) {
return msg;
}
else {
memcpy(out, in, sizeof(oscilloscope_t));
}
uartlen = sizeof(oscilloscope_t);
post uartSendTask();
} else {
message_t *newmsg = call UARTMessagePool.get();
if (newmsg == NULL) {
report_problem();
return msg;
}
//Serial port busy, so enqueue.
out = (oscilloscope_t*)call SerialSend.getPayload(newmsg, sizeof(oscilloscope_t));
if (out == NULL) {
return msg;
}
memcpy(out, in, sizeof(oscilloscope_t));
if (call UARTQueue.enqueue(newmsg) != SUCCESS) {
call UARTMessagePool.put(newmsg);
fatal_problem();
return msg;
}
}
if(counter % 10 == 0){
oscilloscope_t* btrpkt = (oscilloscope_t*)(call Packet.getPayload(&pkt, sizeof(oscilloscope_t)));
call Leds.led1On();
if (call AMSend.send(rec, &pkt, sizeof(oscilloscope_t)) == SUCCESS) {
call Leds.led0On();
sendbusy = TRUE;
}
}
return msg;
}
Once the data sends back to the node from where it received the packet , it is unable to process it through UART again. Could anyone help me how could I solve my problem?
According to the question and comments:
You must instantiate AMSenderC with the same id as for the receiver. In this case, AM_OSCILLOSCOPE if you want a message to be processed by the same code. Or another id plus a new implementation of the Receive interface.
You missed putting payload into btrpkt.
You must check for sendbusy - it is a bug if you try to use the radio stack when it is busy.

Swift 2.0: HTTP GET error handling in Xcode 7

I'm new with xcode programming, I'm trying to implement an App in Swift 2 that makes an HTTP Get request. After upgrading xcode 7 its showing error of:
Cannot convert value of type
'(NSData!, response: NSURLResponse!, err: NSError!) -> ()'
to expected argument type
'(NSData?, NSURLResponse?, NSError?) -> Void'
(This code snippet uses the old error handling of swift 1.2.) Can anyone help me please how to implement this in Swift 2.0.
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler:loadedData)
task.resume()
}
func loadedData(data:NSData!, response:NSURLResponse!, err:NSError!){
if(err != nil)
{
print(err?.description)
}
else
{
var jsonResult: NSDictionary = NSDictionary()
let httpResponse = response as! NSHTTPURLResponse
print("\(httpResponse.statusCode)")
if (httpResponse.statusCode == 200)
{
jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
print(jsonResult)
self.performSegueWithIdentifier("SuccessSignin", sender: self)
}
else if (httpResponse.statusCode == 422){
print("422 Error Occured...")
}
}
}
The method signature has changed (parameters are now optionals). Also, you have to use try enclosed in a do catch block. And avoid using forced try (with !) but prefer catching possible errors, and use if let to safely unwrap optionals. Example:
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
print(error!.description)
} else {
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
do {
if let data = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
self.performSegueWithIdentifier("SuccessSignin", sender: self)
}
} catch let JSONError as NSError {
print(JSONError)
}
} else if (httpResponse.statusCode == 422) {
print("422 Error Occured...")
}
} else {
print("Can't cast response to NSHTTPURLResponse")
}
}
}
task.resume()
Here's the error message that you are receiving:
Cannot convert value of type
'(NSData!, response: NSURLResponse!, err: NSError!) -> ()'
to expected argument type
'(NSData?, NSURLResponse?, NSError?) -> Void'
As is shown in the message, the parameters for the dataTaskWithRequest's completionHandler changed from being forced unwrapped (!) to being just optionals (?).
Notice the ! versus the ?:
// old
(NSData!, response: NSURLResponse!, err: NSError!)
// new
(NSData?, NSURLResponse?, NSError?)
As a result, you need to adjust your code accordingly.
For example, your method declaration will look like this:
func loadedData(data:NSData?, response:NSURLResponse?, err:NSError?)
In addition, evaluate the method body and make sure that you are now properly unwrapping the optional parameters data, response and err.
See the NSURLSession class reference for more information.

System.IndexOutOfRangeException: Cannot find table 0

I got struck with this issue since long and am unable to find a solution
I have been getting this error:
'System.IndexOutOfRangeException: Cannot find table 0.' at line 3:
if (Session["value"] != null)
{
**ds = proxy.GetId(Session["value "].ToString());**
if (ds!= null)
{
if (ds.Tables.Count == 0)
{
Response.Redirect("Timeout.aspx");
}
else
{
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
string Id = ds.Tables[0].Rows[0]["id"].ToString().Trim();
if (Id.Trim() == "0")
{
Session["ID"] = "ID NOT CREATED";
ds = proxy.Getid(Session["value "].ToString());
}
}
}
}
}
Ideally there is only value getting returned from the stored proc,so the error should not occur in line 3, since I put all checks for dataset 'ds' in below code. Request to please help me ...
Have you checked in the function GetId for possible causes for the error or if the session variable you're converting to a string has a value? I can see you getting that error if you're trying to turn a session var into a string when it hasn't been initialized.

Resources