好的,我对 C 套接字还很陌生,但我只需要使用多播套接字执行一些简单的 sendto() 和 recvfrom() 调用即可通过网络获取字符串。在环顾四周并阅读了几本指南(包括 Beej 的)之后,我发现下面的代码可以监听通过多播套接字发送的消息(这是我需要的)。该程序在主程序中运行良好,但是当我将其放入项目其他地方的方法(即称为“listenForPackets”的方法)中并尝试在运行循环的另一个线程中运行它时,我的问题就出现了。但是在调试之后,问题归结为变量“mc_addr_str”,该变量在 main 方法中分配为等于 argv[1]。
#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);
}
现在,通过另一个 SO 成员的帮助,我有一个方法可以将 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 期间是否有转换错误,或者我使用了错误的编码?任何输入表示赞赏!