在Ubuntu下进行Fortran网络编程,需借助外部库实现,核心步骤如下:
安装基础工具与库
gfortran
):sudo apt update && sudo apt install gfortran
。sudo apt install libcurl4-openssl-dev
。编写Fortran代码
program http_get
use iso_c_binding
implicit none
interface
subroutine curl_easy_setopt(curl, option, value) bind(C, name="curl_easy_setopt")
import c_ptr, c_int
type(c_ptr), value :: curl
integer(c_int), value :: option
type(c_ptr), value :: value
end subroutine
function curl_easy_perform(curl) result(res) bind(C, name="curl_easy_perform")
import c_ptr, c_int
type(c_ptr), value :: curl
integer(c_int) :: res
end function
subroutine curl_easy_cleanup(curl) bind(C, name="curl_easy_cleanup")
import c_ptr
type(c_ptr), value :: curl
end subroutine
end interface
type(c_ptr) :: curl
integer(c_int) :: res
curl = curl_easy_init()
if (curl /= c_null_ptr) then
call curl_easy_setopt(curl, CURLOPT_URL, "http://example.com")
res = curl_easy_perform(curl)
if (res /= 0) print *, "Request failed"
call curl_easy_cleanup(curl)
end if
end program
program tcp_client
use iso_c_binding
use socket_module ! 需提前安装libsocket库
implicit none
integer(c_int) :: sock
character(len=100) :: message = "Hello, Server!"
call socket_create(sock)
call socket_connect(sock, [127, 0, 0, 1], 12345) ! 连接本地服务器
call socket_send(sock, message, len_trim(message))
call socket_close(sock)
end program
编译与运行
gfortran -o http_get http_get.f90 -lcurl
。gfortran -o tcp_client tcp_client.f90 -lsocket
。./http_get
或 ./tcp_client
。注意事项:
ISO_C_BINDING
调用C库函数。参考资料: