2011-02-16 62 views
-1

我要爲我的實際項目瘋狂......如何在iPhone ios4.2上的特定端口上收聽?

我有一個設備正在特定端口上發送數據。我的目標是檢測該端口上的所有這類設備。 例如:我在同一網絡上有4種這樣的設備,我會用iPhone檢測所有這些設備。

它使用JAVA發現工具,現在我試圖在我的iPhone上做到這一點。

有在Java中使用的步驟,探索工具:

  • 創建一個DatagramSocket(JAVA)
  • 獲取廣播地址(255.255.255.255)
  • 創建的DatagramPacket(JAVA)
  • 在廣播地址發送數據包與端口30303
  • 進入接收模式
  • 由於套接字,它得到answ ERS包
  • 使用AsyncUdpSocket類提取IP,並從設備的主機名

我試圖repoduce相同的步驟:http://code.google.com/p/cocoaasyncsocket/

這裏是我試過至今代碼:

NSError *e; 
NSString *d = @"abcd"; 
NSData *data = [d dataUsingEncoding:NSUTF8StringEncoding]; 


ssocket = [[AsyncUdpSocket alloc]initWithDelegate:self]; 
[ssocket setDelegate:self]; 



[ssocket enableBroadcast:YES error:&e]; 


[ssocket connectToHost:@"255.255.255.255" onPort:30303 error:&e]; 


[ssocket sendData:data withTimeout:-1 tag:0]; 

[ssocket receiveWithTimeout:-1 tag:0]; 

委託- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port從未被稱爲...

我不知道是什麼是錯誤的..你能給我你對這個問題的意見嗎?如果我使用正確的方法,並看看如果我做錯了什麼?

預先感謝您!

MoKeS

編輯:

我使用Wireshark的嗅探與JavaDiscoverTool和我的應用程序的網絡流量。 實際上,兩個數據包(iphone和javadiscovertool的)之間的差異是源端口。 事實上,在我的應用程序中,源端口與目標端口不同,我認爲這是造成問題的原因。 我需要找到一種方法來強制我發送的數據包的源端口...

任何想法?它在AsyncUdpSocket類上。

+0

你檢查錯誤的對象?這就是他們的優點。 – GorillaPatch 2011-02-16 12:14:47

回答

0

我找到了解決方案。

使用:

NSError *e; 
NSString *d = @"Discovery: Who is out there?\0\n"; 
NSData *data = [d dataUsingEncoding:NSUTF8StringEncoding]; 


ssocket = [[AsyncUdpSocket alloc]initWithDelegate:self]; 
[ssocket setDelegate:self]; 

[ssocket bindToPort:PORT error:&e]; 

[ssocket enableBroadcast:YES error:&e]; 


//[ssocket connectToHost:@"255.255.255.255" onPort:30303 error:&e]; 


//[ssocket sendData:data withTimeout:-1 tag:0]; 

[ssocket sendData:data toHost:@"255.255.255.255" port:30303 withTimeout:-1 tag:0]; 


[ssocket receiveWithTimeout:-1 tag:0]; 

和委託:

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port 
{ 
    NSString* aStr; 

    aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 


    NSLog(@"didreceivedata : %@", aStr); 

    return NO; 


}