Archive

Posts Tagged ‘TwSMS’

TwSMS 發簡訊 (Linux C 版)

一月 21st, 2008

台灣簡訊(TwSMS)是國內一家線上傳簡訊的服務商,提供文字簡訊、語音簡訊等服務,價格也很合理,最重要的是有提供 API 介面,方便用戶在自己的程式中加入發送簡訊功能,官網已經有提供不少範例(PHP/ASP/JSP/Java/Perl/VB/BCB/Delphi),這邊也有 Ruby 的版本,不過就是沒看到 C 的,所以大略寫了一個 Linux C 版本,打算加入自己的嵌入式專題使用。

TwSMS 提供的 API 很簡單,只要由 HTTP 對 API server 發送 Request 即可,接著 server 就會回傳結果。程式先建立一個 socket 連線,然後發送簡訊,最後再擷取回傳碼檢查是否成功。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int main()
{
	/* TWSMS 相關設定 */
	char *username = "username";   // 帳號
	char *password = "password"; // 密碼
	char *type = "now";         // 發送型態
	char *mobile = "0912xxxxxx"; // 電話
	char *message = "簡訊測試"; // 簡訊內容
	char *encoding = "big5";    // 簡訊內容編碼
	char *popup = "";          // 使用 POPUP 顯示
	char *mo = "";             // 使用雙向簡訊
	char *vldtime = "86400";    // 簡訊有效期限(秒)
	char *dlvtime = "";         // 預約時間

	int sockfd;
	int len = 0;
	char *host = "api.twsms.com";
	char msg[512], MSGData[512], buf[512];
	char *res, *checkRes;
	struct sockaddr_in address;
	struct hostent *hostinfo;

	bzero(&address, sizeof(address));
	hostinfo = gethostbyname(host);
	if (!hostinfo) {
		fprintf(stderr, "no host: %s\n", host);
		exit(1);
	}
	address.sin_family = AF_INET;
	address.sin_port = htons(80);
	address.sin_addr = *(struct in_addr *)*hostinfo->h_addr_list;

	/* Create socket */
	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	/* Connect to server */
	if (connect(sockfd, (struct sockaddr *)&address, sizeof(address)) == -1) {
		perror("connect faild!\n");
		exit(1);
	}

	/* Request string */
	len = snprintf(msg, 512,
				  "username=%s&password=%s&type=%s&encoding=%s&popup=%s&mo=%s&mobile=%s"
				  "&message=%s&vldtime=%s&dlvtime=%s", username, password, type, encoding,
				  popup, mo, mobile, message, vldtime, dlvtime);

	/* HTTP request content */
	snprintf(MSGData, 512,
			"POST /send_sms.php HTTP/1.1\r\n"
			"Host: %s\r\n"
			"Content-Length: %d\r\n"
			"Content-Type: application/x-www-form-urlencoded\r\n"
			"Connection: Close\r\n\r\n"
			"%s\r\n", host, len, msg);

	/* Send message */
	send(sockfd, MSGData, strlen(MSGData), 0);

	/* Response message */
	recv(sockfd, buf, 512, 0);

	for (res = strtok(buf, "\n"); strncmp(res, "resp", 4) != 0; res = strtok(NULL, "\n"));
	checkRes = strtok(res, "=");
	checkRes = strtok(NULL, "=");

	if (atoi(checkRes) <= 0) {
		printf("傳送失敗\n");
	} else {
		printf("傳送完成\n");
	}

	close(sockfd);
	return 0;
}

C/C++, 程式筆記 , , ,