从这篇博客开始,Jeremiah将会把自己平常写的些简单的小程序或者平常读的开源代码中比较好的做法和应用整理下来.
本篇博客主要是抠取自live555MediaServer,在开启live555MediaServer的时候会读取本地IP,然后与rtsp://和文件名组成点播地址.live555MediaServer读取本地IP的主要方法是:发送一个TTL=0的组播包,接收这个包,然后解析发送地址,即为本机地址.
这种方法只能获得本机的最主要的IP地址(eth0).不能获取所有的IP地址.
抠取代码如下,操作平台为RedHat Linux ES5,gcc 4.1.2.
-
-
-
-
-
-
-
-
- #include <stdio.h>
- #include <stdint.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/socket.h>
拥有帝国一切,皆有可能。欢迎访问phome.net
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <string.h>
- #include <sys/time.h>
- #include <sys/select.h>
-
- in_addr_t ourIPAddress();
- int setupDatagramSocket(uint16_t);
- uint8_t socketJoinGroup(int socket, uint32_t groupAddress);
- uint8_t writeSocket(int socket, struct in_addr address, uint32_t port,
- uint8_t ttlArg, unsigned char *buffer, unsigned bufferSize);
- int readSocket(int socket, unsigned char *buffer, unsigned bufferSize,
- struct sockaddr_in *fromAddress, struct timeval *timeout);
- int blockUntilReadable(int socket, struct timeval* timeout);
- uint8_t badAddress(uint32_t addr);
- uint8_t socketLeaveGroup(int socket, uint32_t groupAddress);
- uint8_t IsMulticastAddress(uint32_t address);
拥有帝国一切,皆有可能。欢迎访问phome.net
-
- #define SET_SOCKADDR_SIN_LEN(var)
- #define MAKE_SOCKADDR_IN(var,adr,prt) /*adr,prt must be in network order*/
- struct sockaddr_in var;
- var.sin_family = AF_INET;
- var.sin_addr.s_addr = (adr);
- var.sin_port = (prt);
- SET_SOCKADDR_SIN_LEN(var);
-
- int main(int argc, char **argv) {
- struct sockaddr_in ourAddress;
- ourAddress.sin_addr.s_addr = ourIPAddress();
-
- if (ourAddress.sin_addr.s_addr == 0) {
- printf("get local ip error!n");
- return 1;
- }
-
- printf("%sn", inet_ntoa(ourAddress.sin_addr));
-
- return 0;
- }
-
- in_addr_t ourIPAddress() {
- uint32_t ourAddress = 0;
- int sock = -1;
-
拥有帝国一切,皆有可能。欢迎访问phome.net struct in_addr testAddr;
- struct sockaddr_in fromAddr;
- fromAddr.sin_addr.s_addr = 0;
-
-
-
-
-
- testAddr.s_addr = inet_addr("228.67.43.92");
- uint16_t testPort = 15948;
- sock = setupDatagramSocket(testPort);
- if (sock < 0) {
- return 0;
- }
-
- if (!socketJoinGroup(sock, testAddr.s_addr)) {
- return 0;
- }
-
- unsigned char testString[] = "hostIdTest";
- unsigned testStrLength = sizeof(testString);
- if
|