好吧,我對C套接字相當陌生,但我只需要做一些簡單的sendto()和recvfrom()調用,以通過網絡使用多播套接字獲取一個字符串。在環顧四周並閱讀了幾個指南(包括Beej's)之後,我發現下面的代碼可以監聽通過多播套接字發送的消息(這正是我需要的)。程序運行良好,但是在我的項目的其他地方將它放入一個方法(即一個名爲「listenForPackets」的方法)並試圖在runloop的另一個線程中運行時,我的問題就出現了。經過調試後,問題歸結爲變量「mc_addr_str」,該變量在main方法中被賦值爲等於argv [1]。現在Objective-C字符串編碼問題
#include <sys/types.h> // for type definitions
#include <sys/socket.h> // for socket API calls
#include <netinet/in.h> // for address structs
#include <arpa/inet.h> // for sockaddr_in
#include <stdio.h> // for printf() and fprintf()
#include <stdlib.h> // for atoi()
#include <string.h> // for strlen()
#include <unistd.h> // for close()
#define MAX_LEN 1024 // maximum receive string size
#define MIN_PORT 1024 // minimum port allowed
#define MAX_PORT 65535 // maximum port allowed
int main(int argc, char *argv[]) {
int sock; // socket descriptor
int flag_on = 1; // socket option flag
struct sockaddr_in mc_addr; // socket address structure
char recv_str[MAX_LEN+1]; // buffer to receive string
int recv_len; // length of string received
struct ip_mreq mc_req; // multicast request structure
char* mc_addr_str; // multicast IP address
unsigned short mc_port; // multicast port
struct sockaddr_in from_addr; // packet source
unsigned int from_len; // source addr length
// validate number of arguments
if (argc != 3) {
fprintf(stderr,
"Usage: %s <Multicast IP> <Multicast Port>\n",
argv[0]);
exit(1);
}
mc_addr_str = argv[1]; // arg 1: multicast ip address
mc_port = atoi(argv[2]); // arg 2: multicast port number
// validate the port range
if ((mc_port < MIN_PORT) || (mc_port > MAX_PORT)) {
fprintf(stderr, "Invalid port number argument %d.\n",
mc_port);
fprintf(stderr, "Valid range is between %d and %d.\n",
MIN_PORT, MAX_PORT);
exit(1);
}
// create socket to join multicast group on
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
perror("socket() failed");
exit(1);
}
// set reuse port to on to allow multiple binds per host
if ((setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flag_on, sizeof(flag_on))) < 0) {
perror("setsockopt() failed");
exit(1);
}
// construct a multicast address structure
memset(&mc_addr, 0, sizeof(mc_addr));
mc_addr.sin_family = AF_INET;
mc_addr.sin_addr.s_addr = htonl(INADDR_ANY);
mc_addr.sin_port = htons(mc_port);
// bind multicast address to socket
if ((bind(sock, (struct sockaddr *) &mc_addr, sizeof(mc_addr))) < 0) {
perror("bind() failed");
exit(1);
}
// construct an IGMP join request structure
mc_req.imr_multiaddr.s_addr = inet_addr(mc_addr_str);
mc_req.imr_interface.s_addr = htonl(INADDR_ANY);
// send an ADD MEMBERSHIP message via setsockopt
if ((setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void*) &mc_req, sizeof(mc_req))) < 0) {
perror("setsockopt() failed");
exit(1);
}
for (;;) { // loop forever
// clear the receive buffers & structs
memset(recv_str, 0, sizeof(recv_str));
from_len = sizeof(from_addr);
memset(&from_addr, 0, from_len);
// block waiting to receive a packet
if ((recv_len = recvfrom(sock, recv_str, MAX_LEN, 0, (struct sockaddr*)&from_addr, &from_len)) < 0) {
perror("recvfrom() failed");
exit(1);
}
// output received string
printf("Received %d bytes from %s: ", recv_len, inet_ntoa(from_addr.sin_addr));
printf("%s", recv_str);
}
// send a DROP MEMBERSHIP message via setsockopt
if ((setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, (void*) &mc_req, sizeof(mc_req))) < 0) {
perror("setsockopt() failed");
exit(1);
}
close(sock);
}
,通過從其他的會員的幫助下,我有一個將返回名稱IP地址給我一個的NSString(我使用的是其他地方在我的程序也是一個方法,所以我需要保持它返回的NSString )。
-(NSString *)getIPAddress {
NSString *address = @"error";
struct ifaddrs *interfaces; // = NULL;
struct ifaddrs *temp_addr; // = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0)
{
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL)
{
if(temp_addr->ifa_addr->sa_family == AF_INET)
{
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
{
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
我想我可能只是做一個簡單的小轉換
mc_addr_str = (someConversion)getIPAddress;
我至今是:
NSString *ipAddress = [[NSString alloc] initWithString:self.getIPAddress];
mc_addr_str = [ipAddress cStringUsingEncoding:[NSString defaultCStringEncoding]];
當我這樣做,該方案使得使用setsockopt調用,然後失敗,錯誤代碼爲-1(我認爲這是一個通用的錯誤代碼,可以讓程序知道發生了什麼壞事,需要中止)。另外,當我在前面的語句中分配mc_addr_str時,我得到
warning: assignment discards qualifiers from pointer target type
我不確定現在從哪裏出現問題。在分配給mc_addr_str期間,我有鑄造錯誤還是使用了錯誤的編碼?任何輸入是讚賞!
A ** NSString **是*不可變*字符串。編譯器抱怨是因爲你將轉換的結果(也是不可變的)分配給** char ***,並且** char ***指向的字符串可能會被有效地修改。您應該將mc_addr_str聲明爲** const char ***以使警告消失。 – Inshallah 2009-07-23 02:02:36
另外,請嘗試:mc_add_str = [ipAddress UTF8String] – Inshallah 2009-07-23 02:22:19